Skip to content

Instantly share code, notes, and snippets.

@iolo
Created December 10, 2011 08:43
Show Gist options
  • Save iolo/1454837 to your computer and use it in GitHub Desktop.
Save iolo/1454837 to your computer and use it in GitHub Desktop.
emulate html5 classList api with javascript.
(function () {
if (document.documentElement.classList) { // html tag has no 'classList' property
Object.defineProperty(HTMLElement.prototype, 'classList', {
get: function () {
return new function(node) {
var self = node.className.trim().split(/\s+/);
self.item = function (index) {
return self[index];
};
self.contains = function (className) {
return self.indexOf(className) !== -1;
};
self.add = function (className) {
if (!self.contains(className)) {
self.push(className);
node.className = self.toString();
}
};
self.remove = function (className) {
var index = self.indexOf(className);
if (index >= 0) {
self.splice(index, 1);
node.className = self.toString();
}
};
self.toggle = function (className) {
if (self.contains(className)) {
self.remove(className);
} else {
self.add(className);
}
};
self.toString = function() {
return self.join(' ');
};
return self;
}(this);
},
enumerable: true
});
}
}());
@tomolimo
Copy link

Hello,
Could be that a negation is missing on the first line?
I would type:

if (!document.documentElement.classList) { // html tag has no 'classList' property

regards,
Tomolimo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment