JS: iterating over result of getElementsByClassName using Array.forEach

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

    Edit: Although the return type has changed in new versions of HTML (see Tim Down's updated answer), the code below still works.

    As others have said, it's a NodeList. Here's a complete, working example you can try:

    
    
        
            
            
        
        
            

    getElementsByClassName Test

    This is an odd para.

    This is an even para.

    This one is also odd.

    This one is not odd.

    This works in IE 9, FF 5, Safari 5, and Chrome 12 on Win 7.

提交回复
热议问题