Search This Blog

Wednesday, January 27, 2010

Cross-Browser: Getting/Setting the Class Attribute of an Element Using JavaScript

It is common knowledge that getting and setting the class of an element in Internet Explorer requires a bit of a work-around from the standard JavaScript solution that works with all other browsers.

The Usual Way

For example, using setAttribute to set the class requires two different values depending on whether the browser is Internet Explorer (className) or all others (class):
// a conditional statement specifies class or className
var klass = (isIE) ? 'className' : 'class';
element.setAttribute(klass, 'new_class');
The same is also true when attempting to get the class value with getAttribute:
element.getAttribute('className'); // for IE
element.getAttribute('class'); // everybody else
But what if you could both get and set the values on all browsers without any conditional logic? Apparently, you can.

A Better Way

The following solution works in all versions of IE from at least 6 onward, Firefox 3, Chrome, Safari, and Opera 10. I haven't tried it on Konqueror or any of the Linux browsers yet, but I would be surprised if it did not work there equally well.
element.className; // get class(es)
element.className = 'new_class'; // (re)set to single class

// or, if you don't want to tamper with any existing
// classes: note the space before the new class name
element.className = element.className + ' new_class';

// examples
if (/new_class/.test(element.className) { // test = 'solid 1px #555';

if (someVariable == someValue) { // add "new_class" class
    element.className = element.className + ' new_class';
I have created a simple example page. In this case, the script toggles a show and hide class on table rows. Just download a copy from Google Docs, open in your litany of browsers, and enjoy. :)