Convert NodeList to Array in JavaScript
- 1 minute read
Consider the simple HTML snippet:
<div></div>
<div></div>
<div></div>
If we wanted to select all of these div
elements, we could do so using JavaScript’s
document.querySelectorAll method, which will return a
NodeList (and not an array):
const divs = document.querySelectorAll(`div`);
This small utility snippet converts a given NodeList
into an array:
const nodesToArray = (nodeList) => {
return [...nodeList];
};
And here is some example usage for converting that node list of div
elements into an array:
const array = nodesToArray(divs); // Returns [div, div, div]
Conclusion
And that’s one way you can convert a list of nodes into an array in JavaScript. Thanks for reading!