0

Im trying to add items into a div element based on elements from an array. The element I'm trying to add already exists on the page. Basically I'm trying to just create a new version of it and add it to the div.

The code might help explain things further.

JavaScript:

function apply(list) { var item = $("#it_template").children("md-list-item").eq(0); for(var i = 0; i < list.uuids.length; i++){ var uid = list.uuids[i]; item.children("p").eq(0).html(uid); $("#items").append(item); } } 

HTML:

<div id="items"> </div> <div style="display:none" id="it_template"> <md-list-item md-ink-ripple class="list_item"> <p></p> </md-list-item> </div> 

It seems to be faulty somewhere, since whenever I'm running the code I'm only seeing one item being added to the div.

Can you please help me out with where the error is?

6
  • 1
    <md-list-item> isn't a valid html tag. Commented Jul 14, 2016 at 18:46
  • 1
    What is list.uuids? Please show all the relevant code. Also, a JSFiddle with some markup would be nice. Commented Jul 14, 2016 at 18:48
  • 1
    @MarcB at least not now but custom tags are part of the live standard. But has to be registered with document.registerElement('md-list-item'); Commented Jul 14, 2016 at 18:51
  • 1
    @MarcB It might be a library like Polymer which is roughly similar to the official Web Components spec. Commented Jul 14, 2016 at 18:52
  • <md-list-item> is an angular js component @MarcB Commented Jul 14, 2016 at 18:53

2 Answers 2

3

Try this? The important change is cloning the node instead of trying to append it over and over. (A node can only have one parent, so it will just get moved instead of copied.)

Another change I made was to use .text instead of .html. If you're dealing with text, this is generally much better. (Importantly, it reduces your risk of XSS vulnerabilities.)

function apply(list) { var item = $("#it_template").children("md-list-item").eq(0); for(var i = 0; i < list.uuids.length; i++) { var uid = list.uuids[i]; var newItem = item.clone(); newItem.children("p").eq(0).text(uid); $("#items").append(newItem); } } 
Sign up to request clarification or add additional context in comments.

Comments

-1

Unless you are Using Angular Material, <md-list-item> is an invalid tag. Sorry, i am not sure what you are attempting to do but if you want to fill something with a collection of somethings and you want to use Angular. Check out NG-REPEAT directive.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.