Most efficient way to convert an HTMLCollection to an Array

Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an array?

9 s

var arr = htmlCollection )

will have the same effect using “native” code.


Since this gets a lot of views, note (per @oriol’s comment) that the following more concise expression is effectively equivalent:

var arr = [];

But note per @JussiR’s comment, that unlike the “verbose” form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer’s ken.


Since ECMAScript 2015 (ES 6) there is also Array.from:

var arr = Array.from(htmlCollection);


ECMAScript 2015 also provides the spread operator, which is functionally equivalent to Array.from (although note that Array.from supports a mapping function as the second argument).

var arr = [...htmlCollection];

I’ve confirmed that both of the above work on NodeList.

A performance comparison for the mentioned methods:

Leave a Comment