The NodeList
object in JavaScript is an array-like list of nodes (namely, element nodes, attribute nodes, and text odes) extracted from an HTML document.
If you use the querySelectorAll()
method—which most JavaScript developers do quite often—or reference the childNodes
property of an object, then the results will be returned to you in a NodeList
object.
A NodeList
looks like an Array
, and it behaves like an Array
… to an extent. For example, you can iterate on the nodes in a NodeList
using the forEach()
method, just like you can do with the elements of an Array
.
But your options for manipulating the data stored in a NodeList
object are limited. You can’t use the map()
, slice()
, and filter()
methods, and if you need to, it may make sense to convert the NodeList
to an Array
.
So let’s take a look at how you can do that.
How to Convert a NodeList to an Array
Using the Array.from() Method
One way to convert a NodeList
to an Array
is by using the Array.from()
method.
The code snippet below creates an Array
titled myList
from all hyperlinks (that is, <a>
elements) on an HTML page:
const myList = Array.from(document.querySelectorAll('a'));
The nodes will be stored in a flat Array object:
Using the Array Constructor
Another way to convert a NodeList
to an Array
is by using the Array
constructor.
The code snippet below shows you how:
const myList = new Array(document.querySelectorAll('a'));
The nodes will be stored in a nested Array
object:
The Difference Between Array.from() and Array Constructor
Technically, there is none.
Per the specification for the ECMAScript language:
When Array is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.
ECMAScript Language Specification, Section 15.4.1
Aside from one returning a flat array and the other a nested array object, the two methods are generally interchangeable.