return elements that match specified CSS selector(s)

Can I use forEach on the NodeList returned by querySelectorAll()?

Answers:

  • Yes, you can use the forEach method on the NodeList returned by querySelectorAll() in modern JavaScript environments. However, it's important to note that NodeList does not directly have a forEach 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 using Array.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().

Related Questions: