Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Forked from devongovett/gist:1381839
Created November 21, 2011 20:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwaldron/1383813 to your computer and use it in GitHub Desktop.
Save rwaldron/1383813 to your computer and use it in GitHub Desktop.
/*
* Minimal classList shim
* Use with an Array.prototype.indexOf shim to support IE 8
* Derived from work by Devon Govett
* MIT LICENSE
*/
// NOT INTENDED FOR PRODUCTION USE.
if ( !("classList" in document.documentElement) ) {
Object.defineProperty( Element.prototype, "classList", {
get: function() {
var self = this,
rspaces = /\s+/g,
implement;
function classlist() {
return self.className.trim().split(rspaces);
}
function update(fn) {
return function(value) {
var classes = classlist(),
index = classes.indexOf(value);
fn(classes, index, value);
self.className = classes.join(" ");
implement.length = classes.length;
};
}
implement = {
length: (function() {
return classlist().length;
})(),
add: update(function(classes, index, value) {
~index || classes.push(value);
}),
remove: update(function(classes, index) {
~index && classes.splice(index, 1);
}),
toggle: update(function(classes, index, value) {
~index ? classes.splice(index, 1) : classes.push(value);
}),
contains: function(value) {
return !!~classlist().indexOf(value);
},
item: function(i) {
return classlist()[i] || null;
}
};
return implement;
}
});
}
var element = document.getElementById("test");
console.log( element.classList.length );
element.classList.add("ponies");
console.log( element.classList.length );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment