Last Updated: December 26, 2018
·
21.09K
· thomaspeklak

Iterate over querySelectorAll result

querySelectorAll results do not provide a way to iterate over them (what a shame!), it should be as simple as:

document.querySelectorAll('.failure').forEach(function(){
  doStuff()
});

nevertheless you can iterate with:

[].forEach.call(
  document.querySelectorAll('.awsome'), 
  function(el){
    doStuffWith(el);
  }
);

with ES1015 you can use the spread operator to make an array from the query selector result:

 [...document.querySelectorAll('.es2016')].forEach(function () {
    doMoreStuff();
})

3 Responses
Add your response

It's really stupid that you can use forEach on a result from querySelectorAll. Thanks for the tip tho, it helped me.

over 1 year ago ·

NodeList.prototype.forEach = Array.prototype.forEach;
HTMLCollection.prototype.forEach = Array.prototype.forEach;

Quelle: https://gist.github.com/DavidBruant/1016007

over 1 year ago ·

+1

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside