Home  >  Article  >  Web Front-end  >  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?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-20 21:14:02183browse

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:

<input id="check-1" class="check" type="checkbox" name="check">
<input id="check-2" class="check" type="checkbox" name="check">
<input id="check-3" class="check" type="checkbox" name="check">
<input id="check-4" class="check" type="checkbox" name="check">
<input id="check-5" class="check" type="checkbox" name="check">
<input id="check-6" class="check" type="checkbox" name="check">
<input id="check-7" class="check" type="checkbox" name="check">
<input id="check-8" class="check" type="checkbox" name="check">
<input id="check-9" class="check" type="checkbox" name="check">
<input id="check-10" class="check" type="checkbox" name="check" checked="">

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 < checkboxes.length; i++) {
      // Do something with each checkbox
    }

The above is the detailed content of How to Avoid Extra Elements When Looping Through Selected Items with document.querySelectorAll?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn