Thursday, February 7, 2008

Setting class attribute to change style of an element

You can change the class (style) of an attribute in JavaScript.
An easy way to do this is:

element.setAttribute("class","styleClassName");
This works in firefox but not in IE

Another way to do it is:
element.setAttrbute("className", "styleClassName");
This works in IE but not in firefox.

An easy work-around that I found on web and which works on both IE and Firefox is:
element.setAttribute((document.all ? 'className' : 'class'), "styleClassName");

Resources:
http://www.quirksmode.org/bugreports/archives/2005/03/setAttribute_does_not_work_in_IE_when_used_with_th.html
http://www.digitalmediaminute.com/article/1394/the-browser-dom-and-the-class-attribute

No comments: