snippetjavascriptTip
Convert a NodeList to a JavaScript array
Viewed 0 times
javascriptarraynodelistconvert
Problem
If you've ever worked with
Luckily, as
NodeList objects in JavaScript, you might have noticed that they don't have all the array methods available. Seeing as they come up often when querying the DOM, for example using Document.querySelectorAll(), it's useful to know how to convert them to arrays.Luckily, as
NodeList objects are array-like, you can easily convert them to arrays using the spread operator (...). This will allow you to use all the array methods you're used to.Solution
const nodeListToArray = nodeList => [...nodeList];
const nodes = document.childNodes;
// NodeList [ <!DOCTYPE html>, html ]
const nodesArray = nodeListToArray(nodes);
// [ <!DOCTYPE html>, html ]
nodesArray.join(', ');
// '[object DocumentType], [object HTMLHtmlElement]'Code Snippets
const nodeListToArray = nodeList => [...nodeList];
const nodes = document.childNodes;
// NodeList [ <!DOCTYPE html>, html ]
const nodesArray = nodeListToArray(nodes);
// [ <!DOCTYPE html>, html ]
nodesArray.join(', ');
// '[object DocumentType], [object HTMLHtmlElement]'Context
From 30-seconds-of-code: node-list-to-array
Revisions (0)
No revisions yet.