querySelectorAll() the best JavaScript function in the world!

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

1 answer

  1. You can iterate over a NodeList returned by querySelectorAll() using a variety of methods. Here are a few common ways:

    1. Using a for loop:
    ```javascript
    const nodeList = document.querySelectorAll("yourSelector");
    for (let i = 0; i < nodeList.length; i++) {
    console.log(nodeList[i]);
    }
    ```

    2. Using a forEach loop (available in modern browsers):
    ```javascript
    const nodeList = document.querySelectorAll("yourSelector");
    nodeList.forEach((element) => {
    console.log(element);
    });
    ```

    3. Converting NodeList to an Array and using forEach loop:
    ```javascript
    const nodeList = document.querySelectorAll("yourSelector");
    Array.from(nodeList).forEach((element) => {
    console.log(element);
    });
    ```

    4. Using a for...of loop (Modern approach):
    ```javascript
    const nodeList = document.querySelectorAll("yourSelector");
    for (const element of nodeList) {
    console.log(element);
    }
    ```

    Choose the method based on your compatibility and readability requirements. The most modern approach is the for...of loop, but for older browsers, you may want to use a traditional for loop or convert the NodeList to an Array with Array.from() before using forEach.

Related Questions