Setting the class of an element using Javascript

PostFeb 27th, 2006 | Comments (18)
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.

Comments

brindyApr 3, 2006
Thanks for that, just what I was looking for and no doubt has saved me a whole lot of time.
KimJul 6, 2006
Thanks. That saved me a lot of time and frustration!
VInayMay 15, 2007
Hey thanks for that it was a real timely help. Keep up the good work
DanJun 18, 2007
Thanks a lot!
DavidJul 4, 2007
This was just what I was looking for. Thanks!
TimAug 31, 2007
Thanks.
remyaNov 3, 2007
will this work for table row insted of div?????
rakuliDec 13, 2007
Thanks for the tidbit, I was wondering what woul be most compatible, cheers! @ remya, yes it will work for tabke cells if you store the reference in a variable, simplest method is using an ID as displayed above
PaulJan 15, 2008
Worked like a charm! Thank you - this was very useful!
jutika hazarikaJan 21, 2008
How to Set the class of a form element in javascript.
shravan arasJun 27, 2008
thats the thousand time man . :)
LeslieOct 6, 2008
thankyou!
i was using:
document.getElementById('id').class
and i couldnt figure out why it wouldnt work.
thankyou very much ;]
LeeOct 26, 2008
Most excellent dude.
BuntyDec 5, 2008
Thanxxx...really nice one...
ShawnMar 24, 2009
You saved me a bunch of time, thanks!
dharmMar 27, 2009
excellent dude.
PDOct 9, 2009
Nice one! Thanks for posting
jokoOct 21, 2009
Ia have problem, how to set class to be Active at a line of menu, and when other menu link clicked it refresh to be non active..!

Post a comment

Name
URL
Email
Comment