Created
January 13, 2015 14:39
-
-
Save bendc/4090e383865d81b4b684 to your computer and use it in GitHub Desktop.
ES6: Iterating over a NodeList
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var elements = document.querySelectorAll("div"), | |
callback = (el) => { console.log(el); }; | |
// Spread operator | |
[...elements].forEach(callback); | |
// Array.from() | |
Array.from(elements).forEach(callback); | |
// for...of statement | |
for (var div of elements) callback(div); |
Unfortunately Chrome (46 at the time of this writing) doesn't support for...of iteration on NodeLists.
In chrome 51 you can just do elements.forEach(callback)
Array.from(elements, callback)
You also can add custom iterator
elements[Symbol.iterator]();
elements.forEach(callback)
[].forEach.call(elements, callback)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unsurprisingly,
for...of
is approximately twice as fast as the two other approaches.