return elements that match specified CSS selector(s)

How do you iterate over the NodeList returned by querySelectorAll()?

Answers:

  • To iterate over a NodeList returned by the querySelectorAll() method in JavaScript, you have several options. A NodeList is similar to an array but does not have all the array methods. Here are some common ways to iterate over it:

    1. Using a for loop

    You can use a classic for loop to iterate over the NodeList:

    const nodes = document.querySelectorAll('div'); // Example selector
    
    for (let i = 0; i < nodes.length; i++) {
        console.log(nodes[i]); // Access each node
    }
    

    2. Using forEach

    If you want to use a more modern approach, you can convert the NodeList to an array and use the forEach method:

    const nodes = document.querySelectorAll('div');
    
    nodes.forEach(node => {
        console.log(node); // Access each node
    });
    

    3. Using Array.from()

    You can also convert the NodeList to an array using Array.from():

    const nodes = document.querySelectorAll('div');
    
    Array.from(nodes).forEach(node => {
        console.log(node); // Access each node
    });
    

    4. Using the spread operator

    You can convert the NodeList to an array using the spread operator (...):

    const nodes = document.querySelectorAll('div');
    
    [...nodes].forEach(node => {
        console.log(node); // Access each node
    });
    

    5. Using for...of loop

    You can also use the for...of loop, which works directly with iterable objects like NodeList:

    const nodes = document.querySelectorAll('div');
    
    for (const node of nodes) {
        console.log(node); // Access each node
    }
    

    Any of these methods will allow you to effectively iterate over the elements in a NodeList returned by querySelectorAll(). Choose the one that you find most readable and aligns with your coding style!

Related Questions: