cc young cc young - 1 month ago 15
Javascript Question

In Javascript, what is the best way to convert a NodeList to an array

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
?

Answer

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


If you are using a transpiler (for example Babel) an iterator works too:

for (var el of document.querySelectorAll('.my-selector')) { el.classList.add('active'); // example }