Can I use forEach on the NodeList returned by querySelectorAll()?
Answers:
Yes, you can use the
forEach
method on the NodeList returned byquerySelectorAll()
in modern JavaScript environments. However, it's important to note that NodeList does not directly have aforEach
method in older JavaScript versions.Here's how you can use it:
const elements = document.querySelectorAll('.my-elements'); // Returns a NodeList // Using forEach directly on NodeList (works in modern browsers) elements.forEach(element => { console.log(element); // Do something with each element });
If you are targeting older browsers that do not support
forEach
on NodeList, you can convert the NodeList to an array usingArray.from()
or the spread operator (...
). Here's how you can do it:const elements = document.querySelectorAll('.my-elements'); // Convert NodeList to Array and use forEach Array.from(elements).forEach(element => { console.log(element); // Do something with each element }); // Or using the spread operator [...elements].forEach(element => { console.log(element); // Do something with each element });
With these approaches, you can effectively loop through elements selected by
querySelectorAll()
.