re: How do I use .forEach on DOM Elements? VIEW POST


Wait, is this true?

Eventually, I realized that timestamps was not an array, it was a NodeList and at the top of mdn documentation, ...

I seldom use selectElementsByClassName, but according to mdn it returns a HTMLCollection. And the mdn doc clearly says it hasn't got forEach.

But for NodeList, you should be able to do forEach. If you do document.querySelectorAll('.className'), you will get an NodeList and you should be able to do forEach. See here.

Howeverrrrr, since most older browsers won't have NodeList.prototype.forEach defined, it is probably safer to do what you suggested, ...) or just [], ...). A more "es6" way would probably be Array.from(elements).forEach(...).

Orrrrr, you could do it with for-loops as you suggested. "es6" introduced this amazing for-of loop, it could loop through most list-like things. So the following would work as well.

for (const el of elements) {
  // ...

Of course, to safely use ES6 features you probably want your polyfills + babel set up to support old browsers.

code of conduct - report abuse