[thelist] [Easy as Pie] Unobtrusive Javascript

Christian Heilmann codepo8 at gmail.com
Wed Dec 19 10:25:21 CST 2007

> 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++){


In other feedback: Unobtrusive JavaScript is more than providing
wrapper methods and put the event handling out of the HTML, this is a
first step. I am scared of any tutorial that tells me that something
is easy as pie when you use a certain product or script. UJS is a lot
about planning and writing code that checks on each step on the way
what can be done. It also boils down to understanding Event Handling.
This element.onclick way for example is great for explaining a quick
example but does have memory issues on IE.

Opera just reprinted my former article on the subject:

I've also given a workshop in Paris on the matter and posted a
transcript: http://www.wait-till-i.com/2007/11/23/transcript-of-the-paris-web-2007-workshop-on-unobtrusive-javascript/

That said, I like the way you wrote the article and kept people on the
ball with examples along the way.


Chris Heilmann
Book: http://www.beginningjavascript.com
Blog: http://www.wait-till-i.com
Writing: http://icant.co.uk/

More information about the thelist mailing list