Skip to content

Home

Convert a NodeList to a JavaScript array

If you've ever worked with 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.

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]'

More like this

Start typing a keyphrase to see matching snippets.