Jer Jer - 1 year ago 286
Javascript Question

Using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function”

In my JSFiddle, I’m simply trying to iterate over an array of elements. The array is non-empty, as the log statements prove. Yet the call to

gives me the (not so helpful) “Uncaught
is not a function” error.

I must be doing something stupid; what am I doing wrong?

My code:

var arr = document.getElementsByClassName('myClass');
arr.forEach(function(v, i, a) {

.myClass {
background-color: #FF0000;

<div class="myClass">Hello</div>

Answer Source

That's because document.getElementsByClassName returns a HTMLCollection, not an array.

Fortunately it's an "array-like" object (which explains why it's logged as if it was an object and why you can iterate with a standard for loop), so you can do this :

[]'myClass'), function(v,i,a) {

With ES6 (on modern browsers or with Babel), you may also use Array.from which builds arrays from array-like objects:


or spread the array-like object into an array:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download