Moon
Moon

Reputation: 22565

What is best way to create elements and append them to the dom in jquery?

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?

Upvotes: 6

Views: 2952

Answers (3)

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

Upvotes: 8

T.J. Crowder
T.J. Crowder

Reputation: 1073968

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.

Upvotes: 9

dtbarne
dtbarne

Reputation: 8190

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

Upvotes: 8

Related Questions