What's the best way to loop through a set of elements in JavaScript?

前端 未结 14 2027
清歌不尽
清歌不尽 2020-11-27 06:34

In the past and with most my current projects I tend to use a for loop like this:

var elements = document.getElementsByTagName(\'div\');
for (var i=0; i

        
14条回答
  •  囚心锁ツ
    2020-11-27 06:50

    I too advise to use the simple way (KISS !-)

    -- but some optimization could be found, namely not to test the length of an array more than once:

    var elements = document.getElementsByTagName('div');
    for (var i=0, im=elements.length; im>i; i++) {
        doSomething(elements[i]);
    }
    

提交回复
热议问题