Shanzid S. Bidhan Shanzid S. Bidhan - 4 months ago 8
jQuery Question

Appending child nodes on a div

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?

Answer

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);
    }
}