Skip to content

Instantly share code, notes, and snippets.

@TexRx
Created June 5, 2013 04:44
Show Gist options
  • Save TexRx/5711666 to your computer and use it in GitHub Desktop.
Save TexRx/5711666 to your computer and use it in GitHub Desktop.
Pure JS alternatives to common CSS class jQuery functions
function hasClass(elem, className) {
return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
}
function addClass(elem, className) {
if (!hasClass(elem, className)) {
elem.className += ' ' + className;
}
}
function removeClass(elem, className) {
var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, ' ') + ' ';
if (hasClass(elem, className)) {
while (newClass.indexOf(' ' + className + ' ') >= 0 ) {
newClass = newClass.replace(' ' + className + ' ', ' ');
}
elem.className = newClass.replace(/^\s+|\s+$/g, '');
}
}
function toggleClass(elem, className) {
var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, ' ' ) + ' ';
if (hasClass(elem, className)) {
while (newClass.indexOf(' ' + className + ' ') >= 0 ) {
newClass = newClass.replace( ' ' + className + ' ' , ' ' );
}
elem.className = newClass.replace(/^\s+|\s+$/g, '');
} else {
elem.className += ' ' + className;
}
}
/* Usage Examples */
if(hasClass(myElem, 'some-class')) {
// do something here
}
addClass(myElem, 'some-class');
removeClass(myElem, 'some-class');
toggleClass(myElem, 'some-class');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment