-
-
Save dangayle/3e83c5d2ac21d3884512ca36ee0eb0fd to your computer and use it in GitHub Desktop.
Pure JS alternatives to common CSS class jQuery functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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