return elements that match specified CSS selector(s)

What is the best way to iterate over elements from querySelectorAll in JavaScript?

Answers:

  • In JavaScript, there are several effective ways to iterate over elements selected by querySelectorAll. Here are some of the best options:

    1. Using forEach

    NodeList returned by querySelectorAll can be converted to an array, allowing you to use forEach.

    const elements = document.querySelectorAll('your-selector');
    elements.forEach(element => {
        // Your code here
    });
    

    2. Using a for...of loop

    You can directly use for...of to iterate over the NodeList, as it is iterable.

    const elements = document.querySelectorAll('your-selector');
    for (const element of elements) {
        // Your code here
    }
    

    3. Using a traditional for loop

    This method is also valid and very straightforward, especially if you need to implement index-based logic.

    const elements = document.querySelectorAll('your-selector');
    for (let i = 0; i < elements.length; i++) {
        const element = elements[i];
        // Your code here
    }
    

    4. Converting to an Array

    You can convert the NodeList to an array and then use array methods.

    const elements = Array.from(document.querySelectorAll('your-selector'));
    elements.forEach(element => {
        // Your code here
    });
    

    5. Using Array.prototype.forEach.call

    You can use call to invoke forEach directly on the NodeList.

    const elements = document.querySelectorAll('your-selector');
    Array.prototype.forEach.call(elements, element => {
        // Your code here
    });
    

    Conclusion

    The best approach often depends on your specific needs. For readability and simplicity, the forEach method is highly recommended. If you're already using modern JavaScript features, the for...of loop is very clean and straightforward. Choose the one that fits your coding style and project requirements.