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

前端 未结 14 1994
清歌不尽
清歌不尽 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:54

    I like doing:

     
    var menu = document.getElementsByTagName('div');
    for (var i = 0; menu[i]; i++) {
         ...
    }
    

    There is no call to the length of the array on every iteration.

提交回复
热议问题