views:

1160

answers:

3

I'm working on a mobile web app that needs to work in IE Mobile. I've narrowed down a JavaScript error I'm getting to IE Mobile not supporting the 'className' property (IE4 engine...). I'm trying to find an alternative that works across all browsers with minimal code changes (I already have a few libraries that use 'className').

The easiest approach I could think of would be to modify IE's element prototype to include className (if it doesn't have it), the problem is that I don't know what the alternative to 'className' is in IE Mobile.

I've tried this:

element.className = element.class;

Which obviously doesn't work because class is a keyword in JavaScript and my JS compressor doesn't like it, and it's probably not valid anyway.

Other than using 'setAttribute()' everywhere I need to modify an element's class, is there any property I can use that is the equivalent to className?

+1  A: 

No attribute, no. I'm afraid you're stuck with getAttribute() and setAttribute().

chaos
+1  A: 

While you can't avoid using setAttribute(), you can take a line out of the jQuery playbook and use a helper procedure with an optional parameter. This code is untested, but ought to work:

var className = function (obj, value)
{
    if (value !== undefined)
    {
        return obj.setAttribute ('class', value);
    }
    return obj.getAttribute ('class');
};

// Use as
alert (className (element));
className (element, "foo");
alert (className (element));
John Millikin
+1  A: 

Following up on what John Millikin, you could even make that function part of IE's element prototype:

Element.prototype.getClass = function() {
    return obj.getAttribute ('class');
}
Element.prototype.setClass = function(newClass) {
    return obj.setAttribute('class', newClass);
}

or if you want a combo method like John provided ...

Element.prototype.className = function(newClass) {
    if (!newClass)
        return this.getClass();
    return this.setClass(newClass);
}
machineghost
P.S. Given that elements can have multiple classes, you may even (I dunno how complex your app is) want to make these functions advanced enough to add/remove specific classes, without making the user do a ton of string parsing to preserve the existing classes. I'll leave the details of that to you
machineghost