Skip to content

Instantly share code, notes, and snippets.

@jelmerdemaat
Created November 18, 2012 20:37
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save jelmerdemaat/4107273 to your computer and use it in GitHub Desktop.
Save jelmerdemaat/4107273 to your computer and use it in GitHub Desktop.
JavaScript hasClass, addClass, removeClass
// JavaScript hasClass, addClass, removeClass
//source: http://www.avoid.org/?p=78
function hasClass(el, name) {
return new RegExp('(\\s|^)'+name+'(\\s|$)').test(el.className);
}
function addClass(el, name)
{
if (!hasClass(el, name)) { el.className += (el.className ? ' ' : '') +name; }
}
function removeClass(el, name)
{
if (hasClass(el, name)) {
el.className=el.className.replace(new RegExp('(\\s|^)'+name+'(\\s|$)'),' ').replace(/^\s+|\s+$/g, '');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment