Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  71] [ 1]  / answers: 1 / hits: 137410  / 12 Years ago, sat, september 8, 2012, 12:00:00

I am trying loop on selected elements that queried with document.querySelectorAll, but how?



For example I use:



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()


My problem is that at the end this method returns 3 extra items. How can I properly do it?


More From » html

 Answers
33

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.


[#83180] Thursday, September 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jeffery

Total Points: 180
Total Questions: 114
Total Answers: 117

Location: Chad
Member since Mon, Dec 5, 2022
2 Years ago
jeffery questions
Fri, Jan 22, 21, 00:00, 3 Years ago
Wed, Dec 2, 20, 00:00, 4 Years ago
Mon, Apr 13, 20, 00:00, 4 Years ago
Mon, Feb 10, 20, 00:00, 4 Years ago
;