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);
});
for
loop but you can also go with[].forEach.call
which I'd consider idiomatic. 2. I don't expect any of these to be removed in the future, so I'm not sure why you want it more "future proof" than what already works today. If it works on IE and modern browsers, it'd work years from now. 3. Speed is likely not a concern. I doubt any common method will grind your application to a halt. Simple iteration is rarely a bottleneck - performance problems are usually elsewhere. – Fretwell