Created
December 10, 2011 08:43
-
-
Save iolo/1454837 to your computer and use it in GitHub Desktop.
emulate html5 classList api with javascript.
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
(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 | |
}); | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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