-
-
Save rwaldron/1383813 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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