JS: iterating over result of getElementsByClassName using Array.forEach

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

    This is the safer way:

    var elements = document.getElementsByClassName("myclass");
    for (var i = 0; i < elements.length; i++) myFunction(elements[i]);
    
    0 讨论(0)
  • 2020-11-22 07:21

    Or you can use querySelectorAll which returns NodeList:

    document.querySelectorAll('.myclass').forEach(...)
    

    Supported by modern browsers (including Edge, but not IE):
    Can I use querySelectorAll
    NodeList.prototype.forEach()

    MDN: Document.querySelectorAll()

    0 讨论(0)
  • 2020-11-22 07:22

    It does not return an Array, it returns a NodeList.

    0 讨论(0)
  • 2020-11-22 07:27

    Here is a test I created on jsperf: https://jsperf.com/vanillajs-loop-through-elements-of-class

    The most perfomant version in Chrome and Firefox is the good old for loop in combination with document.getElementsByClassName:

    var elements = document.getElementsByClassName('testClass'), elLength = elements.length;
    for (var i = 0; i < elLength; i++) {
        elements.item(i).textContent = 'Tested';
    };
    

    In Safari this variant is the winner:

    var elements = document.querySelectorAll('.testClass');
    elements.forEach((element) => {
        element.textContent = 'Tested';
    });
    

    If you want the most perfomant variant for all browsers it might be this one:

    var elements = document.getElementsByClassName('testClass');
    Array.from(elements).map(
        (element) => {
            return element.textContent = 'Tested';
        }
    );
    
    0 讨论(0)
  • 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
    });
    
    0 讨论(0)
提交回复
热议问题