[thelist] Dereferencing in Javascript

Ben Glassman bglassman at gmail.com
Tue Sep 26 19:14:43 CDT 2006


Hi everyone,

I think that my subject line describes what I'm looking for, but I'm not
entirely sure.

Basically I have a script that I'm writing where I'm just trying to cycle
through some tags (h2 tags for example) and attach an onclick event for them
to show or hide an associated element with a specific id (there are the same
number of h2 tags as there are divs. What ends up happening is that all of
the h2 tags end up just showing and hiding the final div (for example, the
tenth div). The code is below. From what I understand it is because of the
fact that the currentItem variable has a live reference to the variable i
and by the time the for loop ends, all of the headings are set to open and
close the current value of i, which always ends up being 10. So how do I
dereference currentItem so this doesn't happen? Hope I am asking the right
question. I know there are better ways to do this, I try to write my own
scripts as alearning experience before trying to find a better one someone
else wrote. Specifically I know Christian has a expand/collapse script that
is really nice, but I'd appreciate help on this so that I understand the
referencing concept for future scripting.

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';
        }
    }
}

Thanks a lot,

Ben



More information about the thelist mailing list