return elements that match specified CSS selector(s)

How to loop through NodeList returned by querySelectorAll()?

Answers:

  • When you use querySelectorAll() in JavaScript, it returns a NodeList of elements that match the specified selector. To loop through this NodeList, you have several options. Here are some of the most common methods:

    1. Using forEach()

    If you use a modern browser, you can use the forEach() method directly on the NodeList:

    const elements = document.querySelectorAll('.my-class');
    
    elements.forEach(element => {
        console.log(element); // Do something with each element
    });
    

    2. Using a for...of Loop

    The for...of loop allows you to iterate over iterable objects like NodeLists directly:

    const elements = document.querySelectorAll('.my-class');
    
    for (const element of elements) {
        console.log(element); // Do something with each element
    }
    

    3. Using a Traditional for Loop

    You can also use a traditional for loop to iterate through the NodeList:

    const elements = document.querySelectorAll('.my-class');
    
    for (let i = 0; i < elements.length; i++) {
        console.log(elements[i]); // Do something with each element
    }
    

    4. Converting to an Array (if needed)

    If you need to use array methods that are not available on NodeList, you can convert it to an array using Array.from() or the spread operator:

    // Using Array.from()
    const elements = document.querySelectorAll('.my-class');
    const elementsArray = Array.from(elements);
    
    elementsArray.forEach(element => {
        console.log(element); // Do something with each element
    });
    
    // Using the spread operator
    const elementsArray2 = [...elements];
    
    elementsArray2.forEach(element => {
        console.log(element); // Do something with each element
    });
    

    Conclusion

    In modern JavaScript, using forEach() or a for...of loop are the most straightforward approaches for iterating over NodeList elements since they are concise and easy to read. However, if you need the flexibility of array methods, converting the NodeList to an array is the way to go.