How to convert a DOM node list to an array in Javascript?
NodeLists are host objects, using the Array.prototype.slice
method on host objects is not guaranteed to work, the ECMAScript Specification states:
Whether the slice function can be applied successfully to a host object is implementation-dependent.
I would recommend you to make a simple function to iterate over the NodeList
and add each
existing element to an array:
function toArray(obj) {
var array = [];
// iterate backwards ensuring that length is an UInt32
for (var i = obj.length >>> 0; i--;) {
array[i] = obj[i];
}
return array;
}
UPDATE:
As other answers suggest, you can now can use in modern environments the spread syntax or the Array.from
method:
const array = [ ...nodeList ] // or Array.from(nodeList)
But thinking about it, I guess the most common use case to convert a NodeList to an Array is to iterate over it, and now the NodeList.prototype
object has the forEach
method natively, so if you are on a modern environment you can use it directly, or have a pollyfill.
In es6 you can just use as follows:
Spread operator
var elements = [... nodelist]
Using
Array.from
var elements = Array.from(nodelist)
more reference at https://developer.mozilla.org/en-US/docs/Web/API/NodeList