javascript class and className with ie8 and ie7

I often need to access CSS classes to get or set attributes using javascript, and have run into problems with internet explorer support.

Here is a way to change the class of an element by ID:

[code lang="javascript"]
var someId = document.getElementById('nameOfId');
someId.setAttribute('class', "someClassName");
[/code]

This does NOT work in IE6 and IE7 because they recognize className instead of class. I found a nifty way to solve this by using a ternary operator:

[code lang="javascript"]
var someId = document.getElementById('nameOfId');
someId.setAttribute(document.all ? 'className' : 'class', 'someClassName');
[/code]

I thought this was totally awesome UNTIL I found out it doesn’t work with IE8 for some weird reason. I finally found a method of doing it that works in firefox, ie6, ie7, and ie8. It is embarrassingly simple:

[code lang="javascript"]
var someId = document.getElementById('nameOfId');
someId.setAttribute('className', "someClassName") ||
someId.setAttribute('class', "someClassName")
[/code]

This version uses the ‘or’ operator to do the same thing with either ‘className’ or ‘class’. Theoretically, this is doing the same thing as the ternary operator version above. I have no idea why this one works in ie8 and the other one doesn’t. But there you have it!

Also here is another example of using the above method to get the class name (using getAttribute).

This entry was posted in Javascript, ie8 and tagged , , , , . Bookmark the permalink.

Comments are closed.