Wednesday, December 13, 2006


Why are even the simple things sometimes hard? Attempting to get a element attribute. Here is a table of what the various browsers return when trying to get the class attribute having already found an element:
var element = document.getElementById("theSpan");
in a document containing the HTML:
<span id="theSpan" class="something">
Browser element. getAttribute( "class" ); element. getAttribute( "CLASS" ); element. getAttribute( "className" ); element. attributes[ "class" ]; element. className;
Firefox 2.0 something something null [object Attr] something
Opera 9.0 something something null [object Attr] something
Safari 1.3.2 something something null undefined something
IE 5.5 (Mac) null null something something something
IE 7.0 null null something [object] something

Updated: Thanks to anonymous for pointing out that you can just use element.className to get the class name used and it seems to work correctly across all browsers I tested.

It seems that there is no simple way to get the class attribute across browsers. The solution seems to be to get the class attribute and if it undefined try the className attribute. Most other attributes should work fine, it is just that IE doesn't like the class attribute that throws the spanner in the works. Here is the quick testing page.


Anonymous said...

Thanks for posting your research on this one Matthew, saved me a lot of grief this afternoon, and I have a tight deadline!

Andrew Deacon

Anonymous said...

try element.className

Anonymous said...

Thank you for you work.
you save to me a lot of time!!

To set class attribute try this
in FireFox.


in IE 7.0


Daniel Torres

Dat Nguyen said...

Thanks for the comparison table. It was the most helpful thing I found on the Internet concerning this problem.

Anonymous said...

Thanks. I had a similar issue and className was the answer.

matuso2k said...
This comment has been removed by the author.
Anonymous said...

Thank you very much! This post saved the weekend! className...

Blue Rattle said...

Thank you. I was debugging this problem in a Joomla website and this helped a lot.

Neville Shaun said...

Thank you so much, automating IE via VBS is hell when half the DOM methods don't seem to work and the only way to find out seems to be to try them 1 by 1

Then again the above applies to almost anything with VBS

Talk about a load off my mind

Pon Saravanan said...

hi thanks for the post. I was wasting my time for about an hour and found your site.

when are the browsers going to get some standards? making developers job very hard

Anonymous said...

that was so helpfull thank you