Skip to content

Instantly share code, notes, and snippets.

@5509
Created March 31, 2011 01:16
Show Gist options
  • Save 5509/895649 to your computer and use it in GitHub Desktop.
Save 5509/895649 to your computer and use it in GitHub Desktop.
classList(DOMTokenList) polyfills
;(function() {
if ( !Element.__defineGetter__ || Element.prototype.hasOwnProperty("classList") ) return;
function classList(elm) {
this.elm = elm;
}
classList.prototype = {
add: function(klass) {
var _elm = this.elm,
_thisClass = _elm.className;
if ( _elm.classList.contains(klass) ) return false;
if ( !_thisClass || _thisClass.length === 0 ) {
_elm.className = klass;
} else {
_elm.className += " " + klass;
}
},
remove: function(klass) {
var _elm = this.elm,
_thisClass = _elm.className,
_thisClassSplit = _thisClass.split(" "),
i;
if ( !_elm.classList.contains(klass) ) return;
if ( _thisClass === klass ) {
_elm.className = "";
return;
}
for ( i = 0; i < _thisClassSplit.length; i++ ) {
if ( _thisClassSplit[i] !== klass ) continue;
delete _thisClassSplit[i];
break;
}
_elm.className = _thisClassSplit.join(" ");
},
toggle: function(klass) {
var _elm = this.elm;
if ( _elm.classList.contains(klass) ) {
_elm.classList.remove(klass);
} else {
_elm.classList.add(klass);
}
},
contains: function(klass) {
return this.elm.className.indexOf(klass) !== -1;
}
}
Element.prototype.__defineGetter__("classList", function() {
return new classList(this);
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment