Skip to content

Instantly share code, notes, and snippets.

@replete
Forked from devongovett/gist:1381839
Last active August 29, 2015 14:21
Show Gist options
  • Save replete/d70820808bf94f8763da to your computer and use it in GitHub Desktop.
Save replete/d70820808bf94f8763da to your computer and use it in GitHub Desktop.
/*
* Minimal classList shim for IE 9
* By Devon Govett
* MIT LICENSE
*/
if (!("classList" in document.documentElement) && Object.defineProperty && typeof HTMLElement !== 'undefined') {
Object.defineProperty(HTMLElement.prototype, 'classList', {
get: function() {
var self = this;
function update(fn) {
return function(value) {
var classes = self.className.split(/\s+/),
index = classes.indexOf(value);
fn(classes, index, value);
self.className = classes.join(" ");
}
}
var ret = {
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 !!~self.className.split(/\s+/).indexOf(value);
},
item: function(i) {
return self.className.split(/\s+/)[i] || null;
}
};
Object.defineProperty(ret, 'length', {
get: function() {
return self.className.split(/\s+/).length;
}
});
return ret;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment