I'm looking for a future proof way to iterate through a NodeList (ie from element.querySelectorAll(selector)
) as well as be cross-browser compatible. Previously I'd been using the ES6 Spread functionality, however IE doesn't support spreading so I used a shim for it instead. I felt that was a bit overkill and inefficient. I then came across the hack Array.prototype.forEach.call
. It works, but looks smelly to me.
What is the best method to iterate over a NodeList?
I'm partial to backwards compatibility and clean smelling code, but if your answer also works for any of the other criteria below, that would be appreciated.
- Readability
- Future Proofing
- Speed
I've looked at JavaScript iterate through NodeList, which goes over a few methods. However, there's no concern over readability, compatibility, etc. Just if it works.
A few methods I've come across are:
const elems = document.querySelectorAll('img');
[].forEach.call(elems, function (o) { console.log(o) });
[...elems].foreach(function (o) { console.log(o) });
for (var i = 0; i < elems.length; i++) {
console.log(elems[i]);
}
for (var i = elems.length - 1; i >= 0; i--) {
console.log(elems[i]);
}
// User-defined
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
forEach(elems, function (index, value) {
console.log(index, value);
});