Mozilla states that "for of loops will loop over NodeList objects correctly". (source: https://developer.mozilla.org/en-US/docs/Web/API/NodeList) However, this doesn't work in Chrome 43. Is this incorrect documentation or a browser bug?
The copied example code used on a page with checkboxes:
var list = document.querySelectorAll( 'input[type=checkbox]' );
for (var item of list) {
item.checked = true;
}
Since I've successfully used
for..of
in Gecko to iterateNodeList
s, it seems this is a browser bug, or at least a browser lack.Actual working code from a userscript I currently use:
(This also uses
let
, but that's another story.)This is what I do, for a different approach
good from IE9 and above
The docs are correct, but I wouldn't call this a bug. Rather it's a "not yet implemented feature".
There is no standard for this, and there is still active discussion on how the DOM should integrate with ES6. Notice that it is clear that
querySelectorAll
should return something iterable which can be used in afor of
loop (as the common expectation demands), but it's not clear how that should happen (LetNodeList
implement the Iterable interface? Let someElements
collection subclassArray
?).Try utilizing
Array.prototype.entries()
You could also use
Array.prototype.values()
Here's yet another solution for the modern age:
This takes advantage of the spread operator which is supported in Google Chrome 46+, Firefox 16+, and Edge, and just for fun the arrow function.
Edit: This is shipping in Chrome 51.
Jake Archibald posted a simple fix:
And for of loops.