Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ES6: Iterating over a NodeList
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);
@bendc

This comment has been minimized.

Copy link
Owner Author

commented Jan 13, 2015

Unsurprisingly, for...of is approximately twice as fast as the two other approaches.

@kellengreen

This comment has been minimized.

Copy link

commented Dec 1, 2015

Unfortunately Chrome (46 at the time of this writing) doesn't support for...of iteration on NodeLists.

@martinmcwhorter

This comment has been minimized.

Copy link

commented Jun 17, 2016

In chrome 51 you can just do elements.forEach(callback)

@varkadov

This comment has been minimized.

Copy link

commented Aug 1, 2016

Array.from(elements, callback)

@treeskar

This comment has been minimized.

Copy link

commented Sep 1, 2016

You also can add custom iterator

elements[Symbol.iterator]();
elements.forEach(callback)
@mzalazar

This comment has been minimized.

Copy link

commented Jan 3, 2019

[].forEach.call(elements, callback)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.