JQuery has .each()
https://api.jquery.com/jQuery.each/
$('div').each(function(idx){ console.log(idx, this) })
this
being the current element. An advantage of using $.each here is arguably cleaner, more readable code and you also get the benefit of chaining.
However it is worth noting (although probably not relevant for your example) that a for loop will most likely perform (much)better when iterating over large collections of elements. For example you could write it like this;
let test = $('input');
for(let i = 0; i < test.length; i++){
console.log(test[i].checked)
}
Further, for...in will work but 1) chkbox
will be the index of the checkbox in the collection and 2) unlike my first for...
example where i will always be an integer index, for...in
this will loop over all properties of the returned JQuery object. You can use hasOwnProperty(i)
to filter out inherited properties like this;
test = $('input');
for(let i in test){
if(!test.hasOwnProperty(i)) {
continue ;
}
console.log(test[i].checked)
}