Blog Stats
  • Posts - 19
  • Articles - 0
  • Comments - 4
  • Trackbacks - 10

 

JavaScript Performance: Fast DOM Iterator

After numerous tests, this function provides the most performant way to iterate over all the elements in the DOM:

function walkTheDom() {

      var items = document.getElementsByTagName("*");

      var i=items.length;

      var item;

      do

      {

        item = items[i];

        //Do something with item

      }

      while (--i);

}

 


Feedback

# re: JavaScript Performance: Fast DOM Iterator

Gravatar Interesting... can you elaborate on the different methods you tested and the times they took? 3/3/2006 7:51 AM | Patrick Fitzgerald

# re: JavaScript Performance: Fast DOM Iterator

Gravatar Hey Patrick ... you can check out my test page here

http://michaelparsons.ca/javascriptperformance.htm
3/3/2006 8:32 AM | Mike Parsons

# re: JavaScript Performance: Fast DOM Iterator

Gravatar hi mike. i was intersted about you project. (MyAJAXToolKit). is there any news/progress about it? 8/14/2006 4:47 AM | mike

# re: JavaScript Performance: Fast DOM Iterator

Gravatar You got a bug in the code - the first item is out of range. It should read item = items[i-1];

Otherwise: Thanks! 3/9/2008 9:15 AM | Johannes

# re: JavaScript Performance: Fast DOM Iterator

Gravatar i--;
do {
item = items[i];
//Do something with item
}
while(i--);

also the expression in *while* must
be post-decrement instead,
otherwise you'll miss item[0].

cheers
2/26/2009 2:51 AM | Anonymous

# re: JavaScript Performance: Fast DOM Iterator

Gravatar i just understood how it works when applying the suggestion of Johannes. in his fix it must stay pre-increment:

do {
item = items[i-1];
//Do something with item

}
while(--i);
2/26/2009 2:57 AM | Anonymous

Post a comment





 

 

 

Copyright © Michael Parsons