Created
February 12, 2019 19:45
-
-
Save phillippelevidad/4ea840d9e9201dc0ec655e3a5736d828 to your computer and use it in GitHub Desktop.
Pure-javascript functions to add/remove CSS classes.
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
// Adapted from https://stackoverflow.com/a/28344281/484108 | |
// and https://jaketrent.com/post/addremove-classes-raw-javascript/ | |
function hasClass(el, className) { | |
return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)')); | |
} | |
function addClass(el, className) { | |
if (!hasClass(el, className)) el.className += ' ' + className; | |
} | |
function removeClass(el, className) { | |
if (hasClass(el, className)) { | |
var reg = new RegExp('(\\s|^)' + className + '(\\s|$)'); | |
el.className = el.className.replace(reg, ' ').trim(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment