89
votes

The DOM method document.querySelectorAll() (and a few others) return a NodeList.

To operate on the list, e.g. using forEach(), the NodeList must first be converted to an Array.

What's the best way to convert the NodeList to an Array?

11
I think the return value of querySelectorAll() is technically called a NodeList. - jfriend00
from mdm "elementList = document.querySelectorAll(selectors);" - cc young
elementList is the variable name. That same page describes how the type of the return value is a NodeList. - jfriend00
thanks for the correction - fixed in question - cc young

11 Answers

80
votes

With ES6 you can simply do:

const spanList = [...document.querySelectorAll("span")];
71
votes

With ES6 you can use Array.from(myNodeList). Then use your favourite array method.

var myNodeList = document.querySelectorAll('.my-selector');

// ALT 1
Array.from(myNodeList).forEach(function(el) {
  console.log(el);
});

Use an ES6 shim to make this work in older browsers too.


If you are using a transpiler (for example Babel) there are two more alternatives:

var myNodeList = document.querySelectorAll('.my-selector');

// ALT 2
for (var el of myNodeList) {
  el.classList.add('active'); // or some other action
}

// ALT 3
[...myNodeList].forEach((el) => {
  console.log(el);
});
50
votes

You can convert it to an array by using the slice method from the Array prototype:

var elList = document.querySelectorAll('.viewcount');
elList = Array.prototype.slice.call(elList, 0);

Furthermore, if all you need is forEach, you can invoke that from the Array prototype, without coercing it to an array first:

var elList = document.querySelectorAll('.viewcount');
Array.prototype.forEach.call(elList, function(el) {
    console.log(el);
});

In ES6, you can use the new Array.from function to convert it to an array:

Array.from(elList).forEach(function(el) {
    console.log(el);
});

This is currently only in bleeding edge browsers, but if you're using a polyfill service you will have access to this function across the board.


If you're using an ES6 transpiler, you can even use a for..of loop instead:

for (var element of document.querySelectorAll('.some .elements')) {
  // use element here
}
22
votes

Why convert? - just call function of Array directly on element collection ;)

[].forEach.call( $('a'), function( v, i) {
    // do something
});

assuming $ is your alias for querySelectorAll, of course


edit: ES6 allows for even shorter syntax [...$('a')] (works in Firefox only, as of May 2014)

13
votes

2020 update: nodeList.forEach() is now an official standard and supported in all current browsers.

Older browsers can use the polyfill below.

To operate on the list in javascript, e.g. using forEach(), the NodeList must be converted to an Array.

That's not true. .forEach() works in current browsers. If it's missing, you can use a polyfill to add .forEach() from Array to NodeList and it works fine:

if ( ! NodeList.prototype.forEach ) {
  NodeList.prototype.forEach = Array.prototype.forEach;
}

You can now run:

myNodeList.forEach(function(node){...})

To iterate over NodeLists just like Arrays.

This produces much shorter and cleaner code than .call() everywhere.

10
votes

Does it have to be forEach? You could simply use a for loop to iterate over the list:

for (var i = 0; i < elementList.length; i++) {
    doSomethingWith(elementlist.item(i));
}
3
votes

Well, this works for me too:

const elements = Object.values( document.querySelector(your selector here) )

Object.values() returns Array of values of given object. NodeList is object, as is everything in JS.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

But it's not compatible with IE, so i guess Array.prototype.*array_method*.call(yourNodeList) is the best option. With this you can invoke any array method on your NodeList

2
votes

ES6 allows cool ways like var nodeArray = Array.from(nodeList) but my favorite one is the new spread operator.

var nodeArray = Array(...nodeList);
2
votes

That worked with me in ES6

lets assume you have nodelist like that

<ul>
  <li data-time="5:17">Flexbox video</li>
  <li data-time="8:22">Flexbox video</li>
  <li data-time="3:24">Redux video</li>
  <li data-time="5:17">Flexbox video</li>
  <li data-time="7:17">Flexbox video</li>
  <li data-time="4:17">Flexbox video</li>
  <li data-time="2:17">Redux video</li>
  <li data-time="7:17">Flexbox video</li>
  <li data-time="9:54">Flexbox video</li>
  <li data-time="5:53">Flexbox video</li>
  <li data-time="7:32">Flexbox video</li>
  <li data-time="2:47">Redux video</li>
  <li data-time="9:17">Flexbox video</li>

</ul>


const items = Array.from(document.querySelectorAll('[data-time]'));

console.log(items);
2
votes

I use the following because I think it's easiest to read:

const elements = document.getElementsByClassName('element');
[...elements].forEach((element) => {
   // code
});

-1
votes

Assuming elems is a nodeList:

var elems = document.querySelectorAll('select option:checked');

then it can be turned into an array as follows:

var values = [].map.call(elems, function(obj) {
  return obj.value;
});

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Example:_using_map_generically_querySelectorAll