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
?
You can convert it to an array by using the slice method from the Array prototype: var elList = document. querySelectorAll('. viewcount'); elList = Array.
By using Array. from() method: This method returns a new Array from an array like object or iterable objects like Map, Set, etc.
A NodeList may look like an array, but in reality, they both are two completely different things. A NodeList object is basically a collection of DOM nodes extracted from the HTML document. An array is a special data-type in JavaScript, that can store a collection of arbitrary elements.
With ES6 you can simply do:
const spanList = [...document.querySelectorAll("span")];
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With