[thelist] [Easy as Pie] Unobtrusive Javascript

ben morrison morrison.ben at gmail.com
Wed Dec 19 10:38:13 CST 2007


On Dec 19, 2007 4:25 PM, Christian Heilmann <codepo8 at gmail.com> wrote:
> > if( var links = document.getElementById
> > ('mylinks').getElementsByTagName('a') ) {
> >         ....
> > };
> >
> > ?
>
> No, this makes an assumption that there is an element with the ID
> mylinks, and would otherwise throw an error.
>
> > for(var i=0;i<links.length;i++) {
> >         ....
> > };
>
> This is a bad practice, as it'll re-read the length attribute on each
> iteration thus being rather slow. A faster option is to use a second
> variable and cache the length:
>
> for(var i=0,j=links.length;i<j;j++){}
>
> or as you are not using an array but an HTMLcollection that is cached
> you can do:
>
> for(var i=0;links[i];i++){
>
> }

What David and Christian said!

On a similar note I came across this today, scroll down to "Access
NodeLists Directly"

http://www.peachpit.com/articles/article.aspx?p=31567&seqNum=5&rl=1

So we can reduce the code thus:

    function unobtrusifier() {
    	if(document.getElementById('mylinks')) {
    		for(var i=0; (p =
document.getElementById('mylinks').getElementsByTagName('a')[i]);i++)
{
    			p.onclick = function() { alert(this.title); return false; };
    		}
    	}
    };

But wether that is an expensive operation or very readable is another
matter - would that still have to evaluate each time?

ben
-- 
Ben Morrison
http://www.benjaminmorrison.com



More information about the thelist mailing list