Monday, February 9, 2009

Javascript IE setAttribute("class", or getAttribute("class") className error

In Internet explorer the Javascript setAttribute("class", ) or getAttribute("class") method doesn't works or gives error in some versions. So instead of that one case use the "className" attribute for a given DOM element.

Code Snippet and description for this is following

To change "class" attribute of a HTML DOM element we usually use the following syntax

DOMObject.setAttribute("class", "NewCSSClassName");

where "NewCSSClassName" is the name of new CSS class for the HTML DOM element.

This thing works fine in all browsers except IE. In IE to read or write "class" attribute to a HTML DOM element use "className" attribute instead. This "className" attribute works well in all browsers.

So the above code snippet after changing the property will look as below:

DOMObject.className = "NewCSSClassName";