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?
What you’re doing is probably fine for the vast majority of use cases. Your code will eventually call the DOM
appendChildfunction once for eachli, 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.
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.