"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Avoid Extra Elements When Looping Through Selected Items with document.querySelectorAll?

How to Avoid Extra Elements When Looping Through Selected Items with document.querySelectorAll?

Published on 2024-12-13
Browse:554

How to Avoid Extra Elements When Looping Through Selected Items with document.querySelectorAll?

Looping Through Selected Elements with document.querySelectorAll

Problem:
When attempting to loop through elements selected using document.querySelectorAll, the output includes additional, irrelevant items.

Example:

var checkboxes = document.querySelectorAll('.check');
for( i in checkboxes) {
  console.log(checkboxes[i]);
}

Output:












10
item()
namedItem()

The problem arises because document.querySelectorAll returns a NodeList, which is an array-like object. However, NodeList does not support array methods like forEach.

Solution:

To properly loop through the selected elements, convert the NodeList to an array. There are several ways to do this:

  1. Spread Syntax (ES2015 ):

    const divs = [...document.querySelectorAll('div')];
    divs.forEach((div) => {
      // Do something with each div
    });
  2. Array.from():

    const divs = Array.from(document.querySelectorAll('div'));
    divs.forEach((div) => {
      // Do something with each div
    });
  3. Looping over node indices:

    const checkboxes = document.querySelectorAll('.check');
    for (let i = 0; i 
Release Statement This article is reprinted at: 1729429999 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3