How do I convert a NodeList to an array when using querySelectorAll?
Answers:
When you use
querySelectorAllin JavaScript, it returns aNodeList, which is similar to an array but not actually an array. If you want to convert aNodeListto an actual array, you can use several methods. Here are a few common approaches:1. Using
Array.from()The simplest and most modern way is to use
Array.from():const nodeList = document.querySelectorAll('your-selector'); const array = Array.from(nodeList);2. Using the Spread Operator
Another modern method is to use the spread operator
...to spread theNodeListinto an array:const nodeList = document.querySelectorAll('your-selector'); const array = [...nodeList];3. Using
Array.prototype.sliceFor older browsers that may not support modern methods, you can use
Array.prototype.slice:const nodeList = document.querySelectorAll('your-selector'); const array = Array.prototype.slice.call(nodeList);4. Using
forEachto Push to an ArrayYou can also manually push elements from the
NodeListinto a new array:const nodeList = document.querySelectorAll('your-selector'); const array = []; nodeList.forEach(node => array.push(node));Usage Example
Here’s how you can use the first method in a real example:
// Select all <div> elements const divs = document.querySelectorAll('div'); // Convert NodeList to array const divArray = Array.from(divs); // Now you can use array methods on divArray divArray.forEach(div => { console.log(div.innerText); });Choose any of the above methods depending on your coding preference and the browser support you need to maintain. The first two methods (
Array.from()and the spread operator) are preferred for their simplicity and clarity.