Fastest way to convert JavaScript NodeList to Array?

ID : 10102

viewed : 18

Tags : javascriptarraysnodelistjavascript

Top 5 Answer for Fastest way to convert JavaScript NodeList to Array?

vote vote

97

With ES6, we now have a simple way to create an Array from a NodeList: the Array.from() function.

// nl is a NodeList let myArray = Array.from(nl) 
vote vote

82

2021 update: nodeList.forEach() is now standard and supported in all current browsers (around 95% on both dekstop & mobile).

So you can simply do:

document.querySelectorAll('img').forEach(highlight); 

Other cases

If you for some reason want to convert it to an array, not just iterate over it - which is a completely relevant use-case - you can use [...destructuring] or Array.from since ES6

let array1 = [...mySetOfElements]; // or let array2 = Array.from(mySetOfElements); 

This also works for other array-like structures that aren't NodeLists

  • HTMLCollection returned by e.g. document.getElementsByTagName
  • objects with a length property and indexed elements
  • iterable objects (objects such as Map and Set)



Outdated 2010 Answer

The second one tends to be faster in some browsers, but the main point is that you have to use it because the first one is just not cross-browser. Even though The Times They Are a-Changin'

@kangax (IE 9 preview)

Array.prototype.slice can now convert certain host objects (e.g. NodeList’s) to arrays — something that majority of modern browsers have been able to do for quite a while.

Example:

Array.prototype.slice.call(document.childNodes); 
vote vote

77

Here's a new cool way to do it using the ES6 spread operator:

let arr = [...nl]; 
vote vote

63

In ES6 you can either use:

  • Array.from

    let array = Array.from(nodelist)

  • Spread operator

    let array = [...nodelist]

vote vote

55

Some optimizations:

  • save the NodeList's length in a variable
  • explicitly set the new array's length before setting.
  • access the indices, rather than pushing or unshifting.

Code (jsPerf):

var arr = []; for (var i = 0, ref = arr.length = nl.length; i < ref; i++) {  arr[i] = nl[i]; } 

Top 3 video Explaining Fastest way to convert JavaScript NodeList to Array?

Related QUESTION?