views:

261

answers:

2

Hi,

I am using the below js code in order to change the class when a link is clicked.

document.getElementById("gifts").setAttribute("class", "gkvSprite selected");

This is not working in IE but it does in FF and Chrome Then I changed the code to :

document.getElementById("gifts").setAttribute("className", "gkvSprite selected");

Then it worked in IE stopped working in FF and Chrome.

Could someone please help me out here?

Thanks in Advance
Alloi

+2  A: 

(Edited; I misread the question the first time.)

You can reliably use the className property instead of setAttribute:

document.getElementById("gifts").className = "gkvSprite selected";

More generally, there are a couple of attribute names that different browsers treat differently in setAttribute: class vs className, and for vs. htmlFor. Libraries like Prototype, jQuery, and the like will smooth out these differences for you, although (again) in the specific situation of class, you can reliably use the property instead.

T.J. Crowder
Thank you for you help :)
Alloi
+1  A: 

You can go about this in a few ways.

If you want to use setAttribute you can detect which browser the client is using and then use class in IE and classname in Firefox.

The above would work but I would prefer using a div and assigning a new class for that.

somediv.className='gkvSprite selected'

Or as T.J. Crowder said above. Asign via Classname directily.

Morten Anderson
Regarding detecting the browser: In at least 90% of these situations, you're much better off with "feature detection" rather than browser sniffing. In this case, for instance, Prototype checks whether the *actual browser you're using* uses `class` or `className` (by testing it once and remembering what happened). Browser sniffing is prone to failure in a variety of ways, not least getting outdated as browsers evolve. You end up with huge logic chains around browser and browser version...
T.J. Crowder