How can I convert the NodeList from querySelectorAll() into an array?
Answers:
You can convert a
NodeList
obtained fromquerySelectorAll()
into an array using various methods. Here are a few common approaches:1. Using
Array.from()
The simplest way to convert a
NodeList
to an array is by using theArray.from()
method.const nodeList = document.querySelectorAll('your-selector'); const array = Array.from(nodeList);
2. Using the Spread Operator
You can also use the spread operator (
...
) inside an array literal to convert theNodeList
.const nodeList = document.querySelectorAll('your-selector'); const array = [...nodeList];
3. Using
Array.prototype.slice()
If you want a more traditional way, you can use the
slice
method fromArray.prototype
.const nodeList = document.querySelectorAll('your-selector'); const array = Array.prototype.slice.call(nodeList);
4. Using
forEach
(if you want to create a custom array)If you want to manually iterate through the
NodeList
, you can also create an array usingforEach
.const nodeList = document.querySelectorAll('your-selector'); const array = []; nodeList.forEach(node => array.push(node));
Any of these methods will successfully convert a
NodeList
into an array, so you can choose the one that fits your coding style or preferences best!