Can I use forEach with NodeList returned by querySelectorAll()?
Answers:
Yes, you can use
forEach
with aNodeList
returned byquerySelectorAll()
, but you need to convert theNodeList
to an array first becauseNodeList
itself does not have aforEach
method in older JavaScript versions.In modern JavaScript (ES6 and later), you can optionally use the spread operator or the
Array.from()
method to convert aNodeList
to an array. Here’s how you can do it:Using
Array.from()
const nodeList = document.querySelectorAll('selector'); // Replace 'selector' with your actual CSS selector const elementsArray = Array.from(nodeList); elementsArray.forEach(element => { // Do something with each element console.log(element); });
Using the Spread Operator
const nodeList = document.querySelectorAll('selector'); // Replace 'selector' with your actual CSS selector const elementsArray = [...nodeList]; elementsArray.forEach(element => { // Do something with each element console.log(element); });
Using a
for
LoopIf you don't want to convert the
NodeList
, you can also use a regularfor
loop, which works forNodeList
directly:const nodeList = document.querySelectorAll('selector'); // Replace 'selector' with your actual CSS selector for (let i = 0; i < nodeList.length; i++) { const element = nodeList[i]; // Do something with each element console.log(element); }
Conclusion
In summary, while you can't directly use
forEach
on aNodeList
, you can easily convert it to an array or use a loop to iterate through the elements.