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
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]);
}
I like to use a TreeWalker if the set of elements are children of a root node.
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.
Also see my comment on Andrew Hedges' test ...
I just tried to run a test to compare a simple iteration, the optimization I introduced and the reverse do/while, where the elements in an array was tested in every loop.
And alas, no surprise, the three browsers I tested had very different results, though the optimized simple iteration was fastest in all !-)
An array with 500,000 elements build outside the real test, for every iteration the value of the specific array-element is revealed.
Test run 10 times.
Results:
Simple: 984,922,937,984,891,907,906,891,906,906
Average: 923.40 ms.
Optimized: 766,766,844,797,750,750,765,765,766,766
Average: 773.50 ms.
Reverse do/while: 3375,1328,1516,1344,1375,1406,1688,1344,1297,1265
Average: 1593.80 ms. (Note one especially awkward result)
Results:
Simple: 344,343,344,359,343,359,344,359,359,359
Average: 351.30 ms.
Optimized: 281,297,297,297,297,281,281,297,281,281
Average: 289.00 ms
Reverse do/while: 391,407,391,391,500,407,407,406,406,406
Average: 411.20 ms.
Results:
Simple: 278,251,259,245,243,242,259,246,247,256
Average: 252.60 ms.
Optimized: 267,222,223,226,223,230,221,231,224,230
Average: 229.70 ms.
Reverse do/while: 414,381,389,383,388,389,381,387,400,379
Average: 389.10 ms.
I think you have two alternatives. For dom elements such as jQuery and like frameworks give you a good method of iteration. The second approach is the for loop.
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
.