I want to iterate over some DOM elements, I\'m doing this:
document.getElementsByClassName( \"myclass\" ).forEach( function(element, index, array) {
//do s
As already said, getElementsByClassName
returns a HTMLCollection, which is defined as
[Exposed=Window]
interface HTMLCollection {
readonly attribute unsigned long length;
getter Element? item(unsigned long index);
getter Element? namedItem(DOMString name);
};
Previously, some browsers returned a NodeList instead.
[Exposed=Window]
interface NodeList {
getter Node? item(unsigned long index);
readonly attribute unsigned long length;
iterable<Node>;
};
The difference is important, because DOM4 now defines NodeLists as iterable.
According to Web IDL draft,
Objects implementing an interface that is declared to be iterable support being iterated over to obtain a sequence of values.
Note: In the ECMAScript language binding, an interface that is iterable will have “entries”, “forEach”, “keys”, “values” and @@iterator properties on its interface prototype object.
That means that, if you want to use forEach
, you can use a DOM method which returns a NodeList, like querySelectorAll.
document.querySelectorAll(".myclass").forEach(function(element, index, array) {
// do stuff
});
Note this is not widely supported yet. Also see forEach method of Node.childNodes?