A NodeList is an array-like object representing a collection of DOM elements or nodes.
It looks like an array, however, you can not use common array methods like
filter() on a
Read this guide to understand the difference between a
NodeList and an array.
Both NodeLists and arrays have their own prototypes, methods, and properties. You can easily convert a
NodeListto an array if you want to, but not the other way around.
In this article, we'll look at different ways to convert a
NodeList object to an array is by using the
// create a `NodeList` object const divs = document.querySelectorAll('div') // convert `NodeList` to an array const divsArr = Array.from(divs)
The output of the above code is a regular
Array object containing all the nodes returned by the
Array.from() method was introduced in ES6 and creates a new, shallow-copied
Array object from the
NodeList object in modern browsers. For old browsers like IE, you need a polyfill.
Another way to create an
Array object from a
NodeList is by using the spread operator syntax (
// create a `NodeList` object const divs = document.querySelectorAll('div') // convert `NodeList` to an array const divsArr = [...divs]
The ES6's spread operator is a concise and super easy way of converting a
Array.from(), it only works in modern browsers.
Finally, the last way to convert a
NodeList to an
Array object is by using the
call() method to execute the
Array.prototype.slice() method on the
NodeList object as shown below:
// create a `NodeList` object const divs = document.querySelectorAll('div') // convert `NodeList` to an array const divsArr = Array.prototype.slice.call(divs)
You can also use a concise form of the above method:
const divsArr = .slice.call(divs)
Array.prototype.slice.call() works well in all modern and old browsers, including IE 6+. You should use this approach if you want to support the most number of browsers.
forEach() and use all your favorite array methods to do different things.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.