Created
February 9, 2017 05:13
-
-
Save akaramires/307103553bfaa3b65aaff52513afd39f to your computer and use it in GitHub Desktop.
Add/Remove Classes With Raw Javascript
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(el, className) { | |
if (el.classList) | |
return el.classList.contains(className) | |
else | |
return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)')) | |
} | |
function addClass(el, className) { | |
if (el.classList) | |
el.classList.add(className) | |
else if (!hasClass(el, className)) el.className += " " + className | |
} | |
function removeClass(el, className) { | |
if (el.classList) | |
el.classList.remove(className) | |
else if (hasClass(el, className)) { | |
var reg = new RegExp('(\\s|^)' + className + '(\\s|$)') | |
el.className=el.className.replace(reg, ' ') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment