Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

dom

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?

like image 685
Moon Avatar asked May 17 '11 06:05

Moon


People also ask

Which method is used to add components or elements to the DOM?

The simplest, most well-known method of appending an element to the DOM is certainly the appendChild() .

What DOM manipulation method do you use to create elements in bulk and append them all to the DOM at one time?

Methods called on Parent Nodes The append method allows you to append multiple elements or text nodes to a parent node.


3 Answers

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.

like image 145
T.J. Crowder Avatar answered Nov 15 '22 06:11

T.J. Crowder


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);
like image 34
dtbarne Avatar answered Nov 15 '22 08:11

dtbarne


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);
like image 37
StackExchange saddens dancek Avatar answered Nov 15 '22 08:11

StackExchange saddens dancek