Let's say I am adding li elements in javascript code with jQuery.
Example 1:
for(var i=0 i<=5; i++){
var li = $("<li/>");
li.html("teest "+i);
$("#ulid").append(li);
}
I've learned that the above example is a bad practice due to the fact that the loop rebuilds dom each time it hits append(li).
If that is the case, what is the best way to do the exact same thing as the above example?
The simplest, most well-known method of appending an element to the DOM is certainly the appendChild() .
Methods called on Parent Nodes The append method allows you to append multiple elements or text nodes to a parent node.
What you're doing is probably fine for the vast majority of use cases. Your code will eventually call the DOM appendChild
function once for each li
, and I'm pretty sure that's also what all of the answers so far will do. And again, it's probably fine, though it may cause a reflow each time.
In those situations where you absolutely, positively need to avoid causing a DOM reflow on each pass through the loop, you probably need a document fragment.
var i, li, frag = document.createDocumentFragment();
for(i=0; i<=5; i++){
li = $("<li>" + "teest "+i + "</li>");
frag.appendChild(li[0]);
}
$("#ulid").append(frag); // Or $("#ulid")[0].appendChild(frag);
When you append a fragment, the fragment's children are appended, not the actual fragment. The advantage here being that being a single DOM call, you're giving the DOM engine the opportunity to add all the elements and only do a reflow at the end.
You can include the inner HTML in the append text as well as multiple elements at a time, so just build one big string and append it just once.
var append_text = "";
for (i = 0; i <= 5; i++) {
append_text += "<li>test " + i + "</li>";
}
$("#ulid").append(append_text);
The jQuery .append method accepts arrays of elements, so you can do this:
var elems = [];
for(var i=0; i<=5; i++){
var li = $("<li/>");
li.html("teest "+i);
elems.push(li[0]); // Note we're pushing the element, rather than the jQuery object
}
$("#ulid").append(elems);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With