How To Set a Class Name using Javascript in IE and Other Browsers
I was working a client project today had to use a little javascript.
As anyone who’s worked with Javascript knows, Microsoft’s Internet Explorer can be a real pain the butt.
Things that work in Chrome, Firefox, and Safari don’t always work in IE – so you always have to come up with workarounds to make IE, well, work.
One of those things that has to be done differently is setting a class name.
For whatever reason, IE does not support using “setAttribute” to set class names. Instead, in IE, you have to use className = newClass.
Here is a little bit of code that should do the trick:
if (navigator.appName == "Microsoft Internet Explorer") {
document.getElementById("id").className="new_class";
}else{
document.getElementById("id").setAttribute("class", "new_class");
}


October 22nd, 2010 at 9:35 am
Hi!
‘navigator.appName == “Microsoft Internet Explorer”‘ was ok in the previous century, perhaps. Don’t you know that browser detect is a big no-no in JavaScript!
Instead of this code, one should use just the following:
document.getElementById(“id”).className=”new_class”;
because it works everywhere. If you want to test existence of a property, detect the properties, not browser vendors!
How come this post ended up on the first page of Google results?
July 26th, 2011 at 3:45 am
Ya thanks a lot for the solution!!!
It worked for me…!!!