[thelist] [Easy as Pie] Unobtrusive Javascript

David Dorward david at dorward.me.uk
Wed Dec 19 10:19:29 CST 2007

On 19 Dec 2007, at 16:06, Stephen Rider wrote:

> Kind of subsidiary to the topic, but, looking at this code:
> if(document.getElementById('mylinks')) {

This will cleanly degrade if there is no element with the id mylinks  
in the DOM

> Am I correct in believing that that can be written as:
> if( var links = document.getElementById
> ('mylinks').getElementsByTagName('a') ) {

This will throw an error and stop processing JS if there is no  
element with the id mylinks in the DOM.

> linklength = links.length;
> for(var i=0;i<linklength;i++) {
> 	....
> };		

This will get the value of the object's length property and store it  
in a variable, then test that variable each time it goes through the  

> to this:
> for(var i=0;i<links.length;i++) {
> 	....
> };

This will test the value of the object's property each time, which is  
a more expensive operation.

> We can thus reduce your already short 9-line function to a mere 7
> lines.  :)

... but not without a price.

David Dorward

More information about the thelist mailing list