简体   繁体   中英

Iterating through NodeList

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.

  1. Readability
  2. Future Proofing
  3. 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);
});

I recommend to use the MDN's Array.from polyfill

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Polyfill

Array.from(nodeList).forEach(node => {})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM