Array.filter(), and more.
Unfortunately, you can’t use any of these with the elements you get back when using
querySelectorAll(), because it returns a NodeList, not an array.
Today, I’m going to show you how to convert a NodeList to an array so you can take full advantage of all those cool new ES6 array methods.
NodeList vs. Array
What’s the difference between a NodeList and an array anyways? I actually wrote about this last year.
(MDN provides an example using Python with
Converting a NodeList to an Array
So… how do you convert a NodeList to an array?
The original way to handle this was to use the
call() method to run the
Array.prototype.slice() method on your NodeList, like this.
// Get all buttons as a NodeList var btns = document.querySelectorAll('button'); // Convert buttons NodeList to an array var btnsArr = Array.prototype.slice.call(btns);
This works, but it’s a bit verbose. There’s a new method you can use to achieve the same thing:
Array.from() method creates a new array from an existing one, or from an array-like object (which is what a NodeList is).
// Get all buttons as a NodeList var btns = document.querySelectorAll('button'); // Convert buttons NodeList to an array var btnsArr = Array.from(btns);
Array.prototype.slice.call() approach has been around for a long time. It works in all modern browsers, and back to at least IE6.
Array.from() method works in all modern browsers, but has no IE support (only Edge). You can push support back to at least IE9 with a polyfill, though.