views:

42

answers:

3

I want to iterate over some DOM elements, I'm doing this:

document.getElementsByClassName( "myclass" ).forEach( function(element, index, array) {
  //do stuff
});

but I get an error: document.getElementsByClassName("myclass").forEach is not a function

I am using Firefox 3 so I know that both getElementsByClassName and Array.forEach are present. This works fine:

[2, 5, 9].forEach( function(element, index, array) {
  //do stuff
});

Is the result of getElementsByClassName an Array? If not, what is it?

+1  A: 

It does not return an Array, it returns a NodeList.

reko_t
+2  A: 

Is the result of getElementsByClassName an Array?

No

If not, what is it?

As with all DOM methods that return multiple elements, it is a NodeList, see https://developer.mozilla.org/en/DOM/document.getElementsByClassName

David Dorward
+3  A: 

No, it's a NodeList.

In Firefox 3, you can convert it into an Array and then call forEach on it:

var els = document.getElementsByClassName("myclass");
var elsArray = Array.prototype.slice.call(els, 0);
elsArray.forEach(function(el) {
    // Do stuff with the element
    console.log(el.tagName);
});
Tim Down