Skip to content

Instantly share code, notes, and snippets.

@wizard04wsu
Last active November 17, 2015 18:40
Show Gist options
  • Save wizard04wsu/3ec34604d7538303e9f0 to your computer and use it in GitHub Desktop.
Save wizard04wsu/3ec34604d7538303e9f0 to your computer and use it in GitHub Desktop.
Class name functions
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