Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
* 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
You can’t perform that action at this time.