How do you convert the NodeList from querySelectorAll() to an array?
Answers:
You can convert a NodeList obtained from
querySelectorAll()to an array using several methods in JavaScript. Here are a few common approaches:1. Using
Array.from()The simplest and most modern way to convert a NodeList to an array is to use the
Array.from()method:const nodeList = document.querySelectorAll('div'); // example selector const array = Array.from(nodeList);2. Using the Spread Operator
If you're working in an environment that supports ES6, you can also use the spread operator to convert a NodeList to an array:
const nodeList = document.querySelectorAll('div'); const array = [...nodeList];3. Using
Array.prototype.slice.call()In older environments or if you prefer a more traditional approach, you can use
Array.prototype.slice.call():const nodeList = document.querySelectorAll('div'); const array = Array.prototype.slice.call(nodeList);4. Using
forEachand a loopYou can also manually loop through the NodeList and push elements into an array, though this is less concise:
const nodeList = document.querySelectorAll('div'); const array = []; nodeList.forEach(node => { array.push(node); });Summary
Any of these methods will successfully convert a NodeList into an array. The first two methods (
Array.from()and the spread operator) are typically the most concise and preferred in modern JavaScript development.