Skip to content

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


A small correction: you used document.getElementsByClassName which does not return a NodeList but a HTMLCollection. Now, the former does have forEach defined - but it's pretty much the only array method that has been added to its prototype so far.

But it's only a relatively recent addition, so older browsers don't support it - fortunately, the Array#forEach trick works pretty well, down to sufficiently old Internet Explorer versions (probably 6? 5.5? The heck am I saying, that could work for slice, but forEach was added only in IE9...).

A HTMLCollection is a totally different beast... and something that should be avoided in general. It's a live collection that gets updated when the DOM changes. Quite heavy when it comes to memory consumption and CPU usage.

Conclusion: use document.querySelectorAll instead (which returns a NodeList).

... a simple for statement would have worked. And would probably be a bit safer.

I don't agree with that ¯\_(ツ)_/¯
It's true that every browser supports for (duh!), but experience proved that something that iterates over a collection for us is simpler as it doesn't force us to take care of a variable for counting, while the (relatively) complex - although well-known - syntax of for is prone to mistakes.

Mostly caused by distraction and/or boredom 😁

code of conduct - report abuse