Home > Web Front-end > JS Tutorial > body text

How to Properly Loop Through Selected Elements Using document.querySelectorAll?

Patricia Arquette
Release: 2024-10-20 21:12:02
Original
291 people have browsed it

How to Properly Loop Through Selected Elements Using document.querySelectorAll?

Looping Through Selected Elements with document.querySelectorAll

Often in web development, looping over selected elements is necessary. document.querySelectorAll provides an array-like object representing the selected elements. However, issues can arise if iteration is performed directly on the NodeList, resulting in additional items appearing in the output.

To properly loop through selected elements, convert the NodeList to an array using spread syntax. By iterating over the resulting array instead, you can avoid the additional items. This method is ideal for modern JavaScript environments with support for ES2015 and Babel.js.

For instance, if you want to loop over checkboxes using document.querySelectorAll('.check'):

<code class="javascript">var checkboxes = document.querySelectorAll('.check');
var checkboxesArray = [...checkboxes];

checkboxesArray.forEach(checkbox => {
  console.log(checkbox);
});</code>
Copy after login

This code snippet will correctly iterate over only the checkbox elements without any extra items.

The above is the detailed content of How to Properly Loop Through Selected Elements Using document.querySelectorAll?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!