How to loop through selected elements with document.querySelectorAll
for in
loop is not recommended for arrays and array-like objects - you see why. There can be more than just number-indexed items, for example the length
property or some methods, but for in
will loop through all of them. Use either
for (var i = 0, len = checkboxes.length; i < len; i++) {
//work with checkboxes[i]
}
or
for (var i = 0, element; element = checkboxes[i]; i++) {
//work with element
}
The second way can't be used if some elements in array can be falsy (not your case), but can be more readable because you don't need to use []
notation everywhere.
My favorite is using spread syntax to convert the NodeList to an array and then use forEach
for looping.
var div_list = document.querySelectorAll('div'); // returns NodeList
var div_array = [...div_list]; // converts NodeList to Array
div_array.forEach(div => {
// do something awesome with each div
});
I code in ES2015 and use Babel.js, so there shouldn't be a browser support issue.