Skip to content

Instantly share code, notes, and snippets.

@phillippelevidad
Created February 12, 2019 19:45
Show Gist options
  • Save phillippelevidad/4ea840d9e9201dc0ec655e3a5736d828 to your computer and use it in GitHub Desktop.
Save phillippelevidad/4ea840d9e9201dc0ec655e3a5736d828 to your computer and use it in GitHub Desktop.
Pure-javascript functions to add/remove CSS classes.
// 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