开发者

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

Let's say I am 开发者_JS百科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 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜