views:

1058

answers:

2

I am creating a javascript function that would find an anchor in a page (specifically with , not an id) and then iterate through the parents of it until it reached one that contains a certain class. I used the following code and it works fine in Firefox 3.0 but fails at getAttribute in both Firefox 3.5 and Internet Explorer 8.

var tab = document.getElementsByName(headerName).item(0);

while (tab.getAttribute('class') != 'card') {
    tab = tab.parentNode;
}

I know this would be easy in jQuery but I am highly constrained. How has getAttribute been changed in these new browsers and what can I do to fix this?

+4  A: 

Try tab.className?

Rahul
Still works in Firefox 3.0 but not IE8 or FF3.5.
Of course the className property works in FF 3.5 and IE8! I just tried it right now on this page, using Firebug: document.getElementsByClassName("container")[0].className prints out "container" in Firefox 3.5. Or since this page includes jQuery, you can use $('div.container')[0].className which returns "container" in both IE8 and FF 3.5.
Joel Mueller
+1  A: 

So my first guess is that tab is undefined if .className returns nothing.

I'm thinking there is something wrong with

document.getElementsByName(headerName).item(0);

Set a breakpoint on the while loop with Firebug and then type "tab" in the console and hit Enter. If there is no Firebug available for FF 3.5. Try using it to find other ways to get at the desired elements.

Eric Wendelin
Firebug 1.4 beta works fine with FF 3.5
Joel Mueller
Great. No excuses for you early adopters out there, of which I am not one yet.
Eric Wendelin
I think Eric is correct. I can find no evidence that either .getAttribute() or .className are broken in any way in FF 3.5 and IE 8, so I would suspect that something has gone wrong with the retrieval of the DOM element.
Joel Mueller
For example, both of the following work fine on this page using FF 3.5 and IE8: "document.getElementsByName('q').item(0).getAttribute('class')" or "document.getElementsByName('q').item(0).className"Both print out "textbox"
Joel Mueller
Aha! Problem solved. As it turns out, how FF3.5 returns getAttribute is different than FF3.0. If the attribute doesn't exist for a particular element in 3.0, getAttribute returns null while 3.5 returns undefined. Not broken (I don't believe I ever implied that it was broken) but implemented differently.
Then I wonder what the deal is with .className
Eric Wendelin