The Browser DOM and the class Attribute

Just came across a DOM gotcha that I am going to document mostly for my own reuse.

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.

6 Responses to “The Browser DOM and the class Attribute”

  1. Jonathan Snook said on May 4th, 2005 at 8:30 pm

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

  2. Brandt Kurowski said on May 7th, 2005 at 5:47 pm

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

  3. flashape said on May 7th, 2005 at 5:48 pm

    don’t know if you’ know about this one already, but http://www.quirksmode.org/ is anawesome reference site. I also use this handy little funtion as a shortcut for creating new elements:

    http://www.visible-form.com/blog/000166.html

  4. temporist said on May 8th, 2005 at 3:53 pm

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

  5. Antonietta Kies said on December 13th, 2006 at 7:57 pm

    First of all, quirksmode is also one of my favorite resources… PPK is fantastic. Secondly, I suggest rather than testing for presence of document.all (I don’t know off the top of my head whether this property is supported by any other browsers), it is potentially safer to observe the browser’s string name, via navigator.appName etc (hey, and there I go referencing PPK again:
    Browser detection

  6. Sudhanshu said on September 19th, 2007 at 10:26 pm

    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”);