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

前端 未结 14 1979
清歌不尽
清歌不尽 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 07:08

    Note that in some cases, you need to loop in reverse order (but then you can use i-- too).

    For example somebody wanted to use the new getElementsByClassName function to loop on elements of a given class and change this class. He found that only one out of two elements was changed (in FF3).
    That's because the function returns a live NodeList, which thus reflects the changes in the Dom tree. Walking the list in reverse order avoided this issue.

    var menus = document.getElementsByClassName("style2");
    for (var i = menus.length - 1; i >= 0; i--)
    {
      menus[i].className = "style1";
    }
    

    In increasing index progression, when we ask the index 1, FF inspects the Dom and skips the first item with style2, which is the 2nd of the original Dom, thus it returns the 3rd initial item!

提交回复
热议问题