Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reliably set the class attr w/JavaScript on IE, FF, Chrome, etc.?

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, but stopped working in FF and Chrome.

Could someone please help me out here?

like image 506
Alloi Avatar asked Mar 22 '10 07:03

Alloi


People also ask

What to do if JavaScript is not working?

Click Options > Under the Hood. In the Privacy section, click Content settings. Scroll to the JavaScript section and click Allow all sites to run JavaScript (recommended). Close the Options tab and refresh the browser.

Is JavaScript supported by all browsers?

JavaScript is a programming language used to make web pages interactive. Like HTML and CSS, you do not need to install anything to begin writing JavaScript or see it run on your computer. All modern browsers support JavaScript.


2 Answers

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.

like image 99
T.J. Crowder Avatar answered Nov 15 '22 13:11

T.J. Crowder


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.

like image 36
Morten Anderson Avatar answered Nov 15 '22 13:11

Morten Anderson