return elements that match specified CSS selector(s)

Can I use forEach with NodeList returned by querySelectorAll()?

Answers:

  • Yes, you can use forEach with a NodeList returned by querySelectorAll(), but you need to convert the NodeList to an array first because NodeList itself does not have a forEach 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 a NodeList 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 Loop

    If you don't want to convert the NodeList, you can also use a regular for loop, which works for NodeList 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 a NodeList, you can easily convert it to an array or use a loop to iterate through the elements.