Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Faster looping over DOMCollections (See related posts)

var i=0, el;
while (el = document.getElementsByTagName('div').item(i++)) {
    // use el here
}


Calling document.getElementsByTagName('div').item() directly saves the browser from having to return a whole DOMCollection. Using the while loop prevents the browser from ever having to calculate a DOMCollection's length, and gives us a syntactically nicer reference to the current node.

Source: David "liorean" Andersson. Here's an e-mail excerpt:

> DOM implementations are optimised for single element access, and DOMCollections [like document.getElementsByTagName()] are particularly badly optimised since they are dynamic, which means they need to be either polled at regular intervals, event controlled or recollected at each access. So, instead of caching the DOMCollection, you can make the script never have to create a DOMCollection at all. A perfomance win that will be considerable, and that can actually be felt if you're doing DHTML. ... [calling item() directly, the browser] never has to create a dynamic collection, it just searches for the element with the given order, and discards the created list. Browsers do optimise for accessing collection members this way.

Comments on this post

Will_Rickards posts on Mar 24, 2006 at 19:02
Shouldn't it be the following so as not to get the list of div tags in the document with each iteration of the loop?

var i=0; 
var el;
var arrDivs = document.getElementsByTagName('div)
while (el = arrDivs[i++])
   {
   // use el here
   }


Or maybe I'm misunderstanding why checking the length of an array is a problem? Maybe because you are modifying the div list in the loop?

var i=0; 
var el;
var arrDivs = document.getElementsByTagName('div)
var ilen = arrDivs.length;
for (var i = 0; i < ilen; i++)
   {
   el = arrDivs[i];
   // use el here
   }

mrclay posts on Mar 31, 2006 at 14:39
Will: I updated the snippet with a better explanation.

arrDivs = document.getElementsByTagName('div')

This caches the created DOMCollection. Liorean seems to suggest this is more costly than just repeatedly asking for a single item off of gEBTN.

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts