Skip to content

Instantly share code, notes, and snippets.

@dangayle
Forked from TexRx/vanilla-not-jquery.js
Created July 27, 2016 18:55
Show Gist options
  • Save dangayle/3e83c5d2ac21d3884512ca36ee0eb0fd to your computer and use it in GitHub Desktop.
Save dangayle/3e83c5d2ac21d3884512ca36ee0eb0fd 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