Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 793
Tom Avatar asked Oct 21 '08 18:10

Tom


People also ask

How do you change NodeList to array?

In modern JavaScript, the simplest and easiest way to convert a NodeList object to an array is by using the Array. from() method: // create a `NodeList` object const divs = document. querySelectorAll('div'); // convert `NodeList` to an array const divsArr = Array.

Does forEach work on HTMLCollection?

Interestingly enough, forEach works on a nodeList but not an HTMLCollection. There are a few different ways to iterate over an HTMLCollection.


2 Answers

var arr = Array.prototype.slice.call( htmlCollection ) 

will have the same effect using "native" code.

Edit

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

var arr = [].slice.call(htmlCollection); 

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.

Edit

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

var arr = Array.from(htmlCollection); 

Edit

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: http://jsben.ch/h2IFA

like image 176
harpo Avatar answered Oct 12 '22 01:10

harpo


not sure if this is the most efficient, but a concise ES6 syntax might be:

let arry = [...htmlCollection]  

Edit: Another one, from Chris_F comment:

let arry = Array.from(htmlCollection) 
like image 42
mido Avatar answered Oct 12 '22 00:10

mido