Home >Web Front-end >JS Tutorial >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:
Spread Syntax (ES2015 ):
const divs = [...document.querySelectorAll('div')]; divs.forEach((div) => { // Do something with each div });
Array.from():
const divs = Array.from(document.querySelectorAll('div')); divs.forEach((div) => { // Do something with each div });
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!