12 November 2015

Append array of jQuery elements

The best way to append an array of jQuery elements to another in the DOM is by simply passing the array to jQuery.append:

var $elements = [];
for (var i = 0; i < 10; i++) {
    $elements.push($('<div>', { text: 'Element ' + i}));
}

$('#some-element').append($elements);

Way back on November 13th, 2012, jQuery 1.8 was released and it added support for appending a list of jQuery elements. Previously .append(someArray) would only support an array of raw DOM elements. Folks who passed an array of jQuery elements used to get the error:

Could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild]

On the eve of the 3rd anniversary of that jQuery release, all blog posts on the front page of Google for “append array of jQuery elements” still have overly complicated solutions to get around this previously missing feature. So I’m hoping to make a bold leap of progress for JavaScript developers everywhere by shining some light on this 3-year-old feature.

If you’re wondering why people discuss this at all, it’s because manipulating the DOM with JavaScript is dreadfully slow. So, instead of writing code that does something like $('#some-element').append($anotherElement) inside each step of a loop, it’s better to do the append in one step and one DOM update. In early work with jQuery, John Resig started employing DocumentFragments as a creative way to work with DOM elements while deferring the actual update to the page.

For performance results, try out this jsperf test that I setup to verify that jQuery.append(array) is indeed efficient (and ignore the erroneous jsperf error).

<(^_^<) (>^_^)> Happy Birthday jQuery.append($array) <(^_^<) (>^_^)>




Did you find this helpful or fun? paypal.me/mrcoles
comments powered by Disqus

Peter Coles

Peter Coles

is a software engineer living in NYC who is building Superset 💪 and also created GoFullPage 📸
more »

github · soundcloud · @lethys · rss