Iterating over a list of selected elements

How to loop through a NodeList and do something with each element.


There are several ways of iterating through a list of selected elements. First, learn about the for() loop:

var divs = document.querySelectorAll('div'), len = divs.length;

for (var i=0; i<len; i++) {
    divs[i].style.color = "green";
}

As you can see, the NodeList's length is determined before the loop. This approach is faster than using divs.length inside the for statement, because the length would otherwise be read repeatedly for each iteration.

A reverse while() loop is an alternative, even more efficient approach and it also involves less code:

var divs = document.querySelectorAll('div'), i = divs.length;
while (i--) {
divs[i].style.color = "green";
}

Finally, you can use this little trick, that is similar to jQuery's $.each() method:

var divs = document.querySelectorAll('div');

[].forEach.call(divs, function(item) {
item.style.color = "green";
});

Naturally, you can create a helper function with any of these loops inside. In modern browsers (no IE!), you can simply do:

var divs = document.querySelectorAll('div');

divs.forEach(function(item) {
item.style.color = "green";
});

Feedback