Skip to content

Instantly share code, notes, and snippets.

@edgarberm
Created June 10, 2015 09:41
Show Gist options
  • Save edgarberm/e68c91e2bf432c3155f8 to your computer and use it in GitHub Desktop.
Save edgarberm/e68c91e2bf432c3155f8 to your computer and use it in GitHub Desktop.
hasClass, addClass, removeClass
Element.prototype.hasClass = Element.prototype.hasClass || function ( className ) {
return new RegExp( ' ' + className + ' ' ).test( ' ' + this.className + ' ' );
};
Element.prototype.addClass = Element.prototype.addClass || function ( className ) {
if ( !this.hasClass( className ) ) {
this.className += ' ' + className;
}
return this;
};
Element.prototype.removeClass = Element.prototype.removeClass || function ( className ) {
var newClass = ' ' + this.className.replace( /[\t\r\n]/g, ' ' ) + ' ';
if ( this.hasClass( className ) ) {
while ( newClass.indexOf( ' ' + className + ' ' ) >= 0 ) {
newClass = newClass.replace( ' ' + className + ' ', ' ' );
}
this.className = newClass.replace( /^\s+|\s+$/g, ' ' );
}
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment