-
-
Save itrelease/418933 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
/* | |
* classList.js | |
* | |
* Implements a cross-browser element.classList getter. | |
* | |
*/ | |
"use strict"; | |
if (typeof Element !== "undefined") { | |
(function () { | |
var classListProp = "classList"; | |
if (!Element.prototype.hasOwnProperty(classListProp)) { | |
var trim = /^\s+|\s+$/g, | |
setClasses = function (elem, classes) { | |
elem.className = classes.join(" "); | |
}, | |
checkAndGetIndex = function (classes, token) { | |
if (token === "") { | |
throw "SYNTAX_ERR"; | |
} | |
if (/\s/.test(token)) { | |
throw "INVALID_CHARACTER_ERR"; | |
} | |
return classes.indexOf(token); | |
}, | |
classListGetter = function () { | |
var elem = this, | |
classes = elem.className.replace(trim, "").split(/\s+/); | |
return { | |
length: classes.length, | |
item: function (i) { | |
return classes[i] || null; | |
}, | |
contains: function (token) { | |
return checkAndGetIndex(classes, token) !== -1; | |
}, | |
add: function (token) { | |
if (checkAndGetIndex(classes, token) === -1) { | |
classes.push(token); | |
this.length = classes.length; | |
setClasses(elem, classes); | |
} | |
}, | |
remove: function (token) { | |
var index = checkAndGetIndex(classes, token); | |
if (index !== -1) { | |
classes.splice(index, 1); | |
this.length = classes.length; | |
setClasses(elem, classes); | |
} | |
}, | |
toggle: function (token) { | |
if (checkAndGetIndex(classes, token) === -1) { | |
this.add(token); | |
} else { | |
this.remove(token); | |
} | |
}, | |
toString: function () { | |
return elem.className; | |
} | |
}; | |
}; | |
if (Object.defineProperty) { | |
Object.defineProperty(Element.prototype, classListProp, { get: classListGetter }); | |
} else if (Object.prototype.__defineGetter__) { | |
Element.prototype.__defineGetter__(classListProp, classListGetter); | |
} | |
} | |
}()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment