How to convert a DOM node list to an array in Javascript?
I have a Javascript function that accepts a list of HTML nodes, but it expects a Javascript array (it runs some Array methods on that) and I want to feed it the output of Document.getElementsByTagName
that returns a DOM node list.
Initially I thought of using something simple like:
Array.prototype.slice.call(list,0)
And that works fine in all browsers, except of course Internet Explorer which returns the error "JScript object expected", as apparently the DOM node list returned by Document.getElement*
methods is not a JScript object enough to be the target of a function call.
Caveats: I don't mind writing Internet Explorer specific code, but I'm not allowed to use any Javascript libraries such as JQuery because I'm writing a widget to be embedded into 3rd party web site, and I cannot load external libraries that will create conflict for the clients.
My last ditch effort is to iterate over the DOM node list and create an array myself, but is there a nicer way to do that?
Solution 1:
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
Solution 2:
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.
Solution 3:
Using spread (ES2015), it's as easy as: [...document.querySelectorAll('p')]
(optional: use Babel to transpile the above ES6 code to ES5 syntax)
Try it in your browser's console and see the magic:
for( links of [...document.links] )
console.log(links);