JS: iterating over result of getElementsByClassName using Array.forEach

前端 未结 11 2109
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  Happy的楠姐
    2020-11-22 07:28

    The result of getElementsByClassName() is not an Array, but an array-like object. Specifically it's called an HTMLCollection, not to be confused with NodeList (which has it's own forEach() method).

    One simple way with ES2015 to convert an array-like object for use with Array.prototype.forEach() that hasn't been mentioned yet is to use the spread operator or spread syntax:

    const elementsArray = document.getElementsByClassName('myclass');
    
    [...elementsArray].forEach((element, index, array) => {
        // do something
    });
    

提交回复
热议问题