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.
Fastest way to convert JavaScript NodeList to Array?
2021 update: nodeList.forEach() is now standard and supported in all current browsers (around 95% on both desktop & mobile).
So you can simply do:
document.querySelectorAll('img').forEach(highlight);
Other cases
If you for some reason want to convert it to an array, not just iterate over it - which is a completely relevant use-case - you can use [...destructuring]
or Array.from
since ES6
let array1 = [...mySetOfElements];
// or
let array2 = Array.from(mySetOfElements);
This also works for other array-like structures that aren't NodeLists
HTMLCollection
returned by e.g.document.getElementsByTagName
- objects with a length property and indexed elements
- iterable objects (objects such as
Map
andSet
)
Outdated 2010 Answer
The second one tends to be faster in some browsers, but the main point is that you have to use it because the first one is just not cross-browser. Even though The Times They Are a-Changin'
@kangax (IE 9 preview)
Array.prototype.slice can now convert
certain host objects (e.g. NodeList’s)
to arrays — something that majority of
modern browsers have been able to do
for quite a while.
Example:
Array.prototype.slice.call(document.childNodes);
In JavaScript, what is the best way to convert a NodeList to an array?
With ES6 you can simply do:
const spanList = [...document.querySelectorAll("span")];
Node to Array in DOM JS, how it works?
You need to transform the node
in an actual Array object. You can use Array.from to do that:
const nodes = document.querySelectorAll('div')const nodesArray = Array.from(nodes)nodesArray.forEach(console.log)
JavaScript DOM - Using NodeLists and Converting to an Array
You can iterate all the <li>
items in each <ul>
in the page like this while able to separately tell which <ul>
they are in:
var list = document.getElementsByTagName("ul");
for (var i = 0; i < list.length; i++) {
var items = list[i].getElementsByTagName("li");
for (var j = 0; j < items.length; j++) {
console.log(items[j]);
}
}
Or, if you just want all <li>
tags, not broken out by <ul>
:
var items = document.getElementsByTagName("li");
for (var i = 0; i < items.length; i++) {
console.log(items[i]);
}
A nodeList or HTMLCollection can be iterated with a simple for
loop as seen above. These objects do not have array methods, but can be copied into an array if you really want to use array methods.
Note, it is probably simpler to use document.querySelectorAll()
for listing all the <li>
elements and you may want to target a specific <ul>
tag by putting an id on it in case there are other <ul>
and <li>
elements in the page.
<ul id="buglist">
<li>Horse Flies</li>
<li>Bed bugs</li>
<li>Mosquito</li>
<li>Ants</li>
<li>Mites</li>
<li>Cricket</li>
<li>Woolly Bear Caterpillar</li>
<li>Fleas</li>
<li>Worms</li>
<li>Leeches</li>
</ul>
var items = document.querySelectorAll("#buglist li");
for (var j = 0; j < items.length; j++) {
console.log(items[j]);
}
A nodeList or HTMLCollection can be copied into an array like this:
var list = Array.prototype.slice.call(document.querySelectorAll("#buglist li"), 0);
list.forEach(function(item) {
console.log(item);
});
Convert NodeList to array
First, don't use document.all
-- it's non-standard and deprecated. Use document.getElementsByTagName
to get the DIV elements in your case.
Second, don't extend DOM objects such as NodeList
-- built-in objects are a very strange breed and are not required to behave like any other objects that you generally work with. See this article for an in-depth explanation of this: What's wrong with extending the DOM.
Related Topics
Replace HTML Page With Contents Retrieved Via Ajax
Intercept a Form Submit in JavaScript and Prevent Normal Submission
Convert Svg to Png With Applied Images as Background to Svg Elements
JavaScript - Shuffle HTML List Element Order
Is There a Callback on Completion of a Css3 Animation
Force "Landscape" Orientation Mode
How to Access the Correct 'This' Inside a Callback
Getcurrentposition() and Watchposition() Are Deprecated on Insecure Origins
How to Use Sockets in JavaScript\Html
How to Use External ".Js" Files
Select All Elements With a "Data-Xxx" Attribute Without Using Jquery
Set Active Tab Style With Angularjs