JS: iterating over result of getElementsByClassName using Array.forEach

前端 未结 11 1919
伪装坚强ぢ
伪装坚强ぢ 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: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';
        }
    );
    

提交回复
热议问题