JS: iterating over result of getElementsByClassName using Array.forEach

前端 未结 11 2200
伪装坚强ぢ
伪装坚强ぢ 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:09

    getElementsByClassName returns HTMLCollection in modern browsers.

    which is array-like object similar to arguments which is iteratable by for...of loop see below what MDN doc is saying about it:

    The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, Array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

    example

    for (const element of document.getElementsByClassName("classname")){
       element.style.display="none";
    }
    

提交回复
热议问题