Last active
November 17, 2015 18:40
-
-
Save wizard04wsu/3ec34604d7538303e9f0 to your computer and use it in GitHub Desktop.
Class name functions
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 removeClass(elem){ | |
var classes, rxp; | |
if(!elem){ | |
throw new Error("Missing parameter: elem"); | |
} | |
classes = Array.prototype.slice.call(arguments, 1).join(" ").trim(); | |
if(!classes || !elem.className.trim()) return; | |
if(!(/^$|^([a-z][a-z0-9_-]*)(\s+[a-z][a-z0-9_-]*)*$/i).test(classes)){ | |
throw new Error("Invalid class name(s)"); | |
} | |
classes = classes.split(/\s+/).join("|"); | |
rxp = new RegExp("^\\s*(?:(?:"+classes+")(?:\\s+|$))+|(?:\\s+(?:"+classes+"))+(?:(\\s)\\s*|$)"); | |
elem.className = elem.className.replace(rxp, "$1").trim(); | |
} | |
function addClass(elem){ | |
var classes, classesRxp, rxp; | |
if(!elem){ | |
throw new Error("Missing parameter: elem"); | |
} | |
classes = Array.prototype.slice.call(arguments, 1).join(" ").trim(); | |
if(!classes) return; | |
if(!(/^([a-z][a-z0-9_-]*)(\s+[a-z][a-z0-9_-]*)*$/i).test(classes)){ | |
throw new Error("Invalid class name(s)"); | |
} | |
classes = classes.split(/\s+/); | |
classesRxp = classes.join("|"); | |
rxp = new RegExp("^\\s*(?:(?:"+classesRxp+")(?:\\s+|$))+|(?:\\s+(?:"+classesRxp+"))+(?:(\\s)\\s*|$)"); | |
elem.className = (elem.className.replace(rxp, "$1") + " "+classes.join(" ")).trim(); | |
} | |
function hasClass(elem){ | |
var classes, i, rxp; | |
if(!elem){ | |
throw new Error("Missing parameter: elem"); | |
} | |
classes = Array.prototype.slice.call(arguments, 1).join(" ").trim(); | |
if(!classes || !elem.className.trim()) return false; | |
if(!(/^([a-z][a-z0-9_-]*)(\s+[a-z][a-z0-9_-]*)*$/i).test(classes)){ | |
throw new Error("Invalid class name(s)"); | |
} | |
classes = classes.split(/\s+/); | |
for(i=0; i<classes.length; i++){ | |
rxp = new RegExp("(^|\\s)"+classes[i]+"(\\s|$)"); | |
if(!rxp.test(elem.className)) return false; | |
} | |
return true; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment