Convert a NodeList to an Array
The document.querySelectorAll()
function returns a NodeList
. That is somewhat similar to an Array, but it's not exactly one.
For example, let's collect all div
s on a page:
const divs = document.querySelectorAll("div");
This has a length
property, and the elements are accessible via their indices:
divs.length; // 2
divs[0].id; // first
This is a so-called Array-like object in Javascript. But since it's not an Array, not all of the functions are available:
divs.map((div) => div.id); // Error
This is a source of confusion. Therefore, it's best to convert it to an Array.
Convert a NodeList
to an Array
To convert an Array-like object to a full-fledged Array, use Array.from
:
Array.from(divs)
.map((div) => div.id);
This is well supported by browsers and states the intention better than the [].concat
, or Array.prototype.slice.call
or the similar solutions.
Use the Array destructuring operator
It wasn't always the case but now the NodeList
is also an iterable, which means it supports the standard iteration protocol. This makes it compatible with the Array destructuring operator, thus enabling a shorter syntax to convert to an Array:
[...divs]
.map((div) => div.id)