Dan Herbert
Dan Herbert

Reputation: 103407

Alternative to 'className' in JavaScript for IE Mobile?

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?

Upvotes: 1

Views: 4258

Answers (3)

machineghost
machineghost

Reputation: 35790

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);
}

Upvotes: 1

John Millikin
John Millikin

Reputation: 200796

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));

Upvotes: 2

chaos
chaos

Reputation: 124297

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

Upvotes: 1

Related Questions