55/95

Loop over a nodelist

Assume that elements is a NodeList that matches given selector:

const elements = document.querySelectorAll(...);

You can loop over elements by using one of the approach below:

1. Use the ES6 spread operator

[...elements].forEach(function(ele) {
    ...
});

2. Use the Array methods

// `Array.from` is not supported on IE
Array.from(elements).forEach(function(ele) {
    ...
});

// Or
[].forEach.call(elements, function(ele) {
    ...
});

// Or
[].slice.call(elements, 0).forEach(function(ele) {
    ...
});

3. Use the forEach method

If you don't have to support Internet Explorer, then use the forEach method:

elements.forEach(function(ele) {
    ...
});

Might be useful