Skip to content

Instantly share code, notes, and snippets.

@willread
Created August 3, 2012 04:40
Show Gist options
  • Save willread/3244444 to your computer and use it in GitHub Desktop.
Save willread/3244444 to your computer and use it in GitHub Desktop.
Utility methods for adding, removing, checking for and toggling classes in classNames.
var hasClass = function(el, c){
return new RegExp("(\\s|^)" + c + "(\\s|$)", "g").test(el.className);
}
var addClass = function(el, c){
if(!this.hasClass(el, c)) el.className += " " + c;
}
var removeClass = function(el, c){
el.className = el.className.replace(new RegExp("(\\s|^)" + c + "(\\s|$)", "g"), " ").trim();
}
var toggleClass = function(el, c){
if(this.hasClass(el, c))
this.removeClass(el, c);
else
this.addClass(el, c);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment