JS: iterating over result of getElementsByClassName using Array.forEach

前端 未结 11 1945
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 06:42

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

document.getElementsByClassName( \"myclass\" ).forEach( function(element, index, array) {
  //do s         


        
11条回答
  •  悲&欢浪女
    2020-11-22 07:13

    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?

提交回复
热议问题