Skip to content

Instantly share code, notes, and snippets.

@wizard04wsu

wizard04wsu/classnames.js

Last active Nov 17, 2015
Embed
What would you like to do?
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