The Browser DOM and the class Attribute

by Tom

Just came across a DOM gotcha that I am going to document mostly for my own reuse.  I use this site periodically for exactly this purpose; I know that this will be a helpful reminder for me in the future, and I have a feeling it might help a few others as well.

Seems that element.setAttribute(“class”, “somename”) works in Firefox and Safari, but not IE. The gotca is that IE requires element.setAttribute(“className”, “somename”).

So for every element.setAttribute(“class”, “somename”) you use, you need to add an extra element.setAttribute(“className”, “somename”) or if you prefer to do it all on one line, you can use the following syntax:

element.setAttribute((document.all ? ‘className’ : ‘class’), “somename”);

This will create the class attribute in both IE and the other browsers.

If you found this helpful or interesting, please share it!

{ 4 comments… read them below or add one }

Jonathan Snook

Have you tested that in Opera? Opera, v7.5 at least, will accept document.all and would therefore use className and not class.

Brandt Kurowski

or you could use element.className = “somename”; which works in all of them.

temporist

className should work in all browsers and i think this is even the conform way to handle it

Sudhanshu

element.setAttribute((document.all ? ‘className’ : ‘class’), “somename”);
instead of the above use the following by putting ” in place of ‘
element.setAttribute((document.all ? “className” : “class”), “somename”);

Leave a Comment

Previous post:

Next post: