[thelist] Dereferencing in Javascript

Christian Heilmann codepo8 at gmail.com
Wed Sep 27 01:13:33 CDT 2006


> var headings = document.getElementsByTagName('h2');
>
> for(i = 0; i<headings.length; i++) {
>     var currentItem = document.getElementById('domain' + i);
>     headings[i].onclick = function() {
>         if (currentItem.className == 'show') {
>             currentItem.className = 'hide';
>         } else if (currentItem.className == 'hide') {
>             currentItem.className = 'show';
>         }
>     }
> }

This is a scope issue. Inside the anonymous function you define i is
not defined as the current counter of the loop but will always be the
final value of i. The quickest way around the issue is to define an
own property of headings and use this, although I'd strongly advise to
use an addEvent handler to do things like that.

> for(i = 0; i<headings.length; i++) {
headings[i].i = i;
>     headings[i].onclick = function() {
>     var currentItem = document.getElementById('domain' + this.i);
>         if (currentItem.className == 'show') {
>             currentItem.className = 'hide';
>         } else if (currentItem.className == 'hide') {
>             currentItem.className = 'show';
>         }
>     }
> }


-- 
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