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.
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