Setting the class of an element using Javascript
setAttribute("class") vs setAttribute("className") vs .className
Recently, I found out the hard way that there are basically three ways to set and/or change the class of an element using Javascript. One works for all major non-IE browsers, one works for IE, and one works for both.
Let's say we have a simple <div> tag:
<div id="test">TEST</div>
Our goal is to assign the "pad_it" class to it via Javascript:
.pad_it {
padding: 20px;
}
Option 1: setAttribute("class")
This solution works for all major non-IE browsers (e.g. Firefox, Safari, Netscape).
Option 2: setAttribute("className")
This solution works for IE but not for any other major browsers.
If you want to go the setAttribute route, you have to use both setAttribute formats:
var thediv = getElementById("test");
thediv.setAttribute("class","pad_id");
thediv.setAttribute("className","pad_id");
This will work in all browsers, but it involves some unnecessary code. Which brings us to the third option.
Option 3: .className
You can set the className attribute directly. This solution works for all major browsers.
var thediv = getElementById("test");
thediv.className = "pad_id";
I hope this clears up some confusion for other web developers out there who may be having the same troubles I recently had.
Recently, I found out the hard way that there are basically three ways to set and/or change the class of an element using Javascript. One works for all major non-IE browsers, one works for IE, and one works for both.
Let's say we have a simple <div> tag:
<div id="test">TEST</div>
Our goal is to assign the "pad_it" class to it via Javascript:
.pad_it {
padding: 20px;
}
Option 1: setAttribute("class")
This solution works for all major non-IE browsers (e.g. Firefox, Safari, Netscape).
Option 2: setAttribute("className")
This solution works for IE but not for any other major browsers.
If you want to go the setAttribute route, you have to use both setAttribute formats:
var thediv = getElementById("test");
thediv.setAttribute("class","pad_id");
thediv.setAttribute("className","pad_id");
This will work in all browsers, but it involves some unnecessary code. Which brings us to the third option.
Option 3: .className
You can set the className attribute directly. This solution works for all major browsers.
var thediv = getElementById("test");
thediv.className = "pad_id";
I hope this clears up some confusion for other web developers out there who may be having the same troubles I recently had.

i was using:
document.getElementById('id').class
and i couldnt figure out why it wouldnt work.
thankyou very much ;]