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

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

    At the risk of getting yelled at, i would get a javascript helper library like jquery or prototype they encapsulate the logic in nice methods - both have an .each method/iterator to do it - and they both strive to make it cross-browser compatible

    EDIT: This answer was posted in 2008. Today much better constructs exist. This particular case could be solved with a .forEach.

提交回复
热议问题