I have JavaScript code that adds and removes classes using the classList
object.
The code is up and working correctly as expected until I received complaints about it because it does not work in Opera and in IE8.
I don't want to use any frameworks or code libraries. I'd like to reduce to a max the code I have to change in my program so I wanted to make my own classList
object and add it to the node object. I already have this code:
if (typeof(document.createElement('input').classList) == 'undefined') {
HTMLElement.prototype.classList = new function () {
this.add = function (addClass) {
this.className += addClass;
}
}
}
which, obviously, does not work.
The problem is: I can't access the HTMLElement.className
of this object like this. How can I accompl开发者_StackOverflow社区ish that? How can I make this object to work similar to or exactly like the original?
Mozilla has listed a classList shim here:
http://developer.mozilla.org/en/DOM/element.classList
There's quite a bit going on in the code, but looks to be what you are after.
Instead of extending the prototype you can just create a helper function that returns the values you need:
classList = function ( elem ) {
return elem.className.replace(/\s+/g,' ').split(' ');
};
Then instead of calling elem.classList
you'd just call classList(elem)
, meaning it doesn't work exactly like the original but it returns the same data.
精彩评论