"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 Properly Loop Through Selected Elements Using document.querySelectorAll?

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

Published on 2024-11-08
Browse:827

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'):

var checkboxes = document.querySelectorAll('.check');
var checkboxesArray = [...checkboxes];

checkboxesArray.forEach(checkbox => {
  console.log(checkbox);
});

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

Release Statement This article is reproduced at: 1729429875 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