jQuery appending an array of elements

2019-01-22 10:44发布

For the purpose of this question lets say we need to append() 1000 objects to the body element.

You could go about it like this:

for(x = 0; x < 1000; x++) {
    var element = $('<div>'+x+'</div>');
    $('body').append(element);
}

This works, however it seems inefficient to me as AFAIK this will cause 1000 document reflows. A better solution would be:

var elements = [];
for(x = 0; x < 1000; x++) {
    var element = $('<div>'+x+'</div>');
    elements.push(element);
}
$('body').append(elements);

However this is not an ideal world and this throws an error Could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild]. I understand that append() can't handle arrays.

How would I using jQuery (I know about the DocumentFragment node, but assume I need to use other jQuery functions on the element such as .css()) add a bunch of objects to the DOM at once to improve performance?

8条回答
姐就是有狂的资本
2楼-- · 2019-01-22 11:41

Since $.fn.append takes a variable number of elements we can use apply to pass the array as arguments to it:

el.append.apply(el, myArray);

This works if you have an array of jQuery objects. According to the spec though you can append an array of elements if you have the DOM elements. If you have an array of html strings you can just .join('') them and append them all at once.

查看更多
Summer. ? 凉城
3楼-- · 2019-01-22 11:42

Upgrade to jQuery 1.8, this works as intended:

​$('body')​.append([
    '<b>1</b>',
    '<i>2</i>'   
])​;​
查看更多
登录 后发表回答