Created
May 24, 2018 21:31
-
-
Save techieshark/778825d935bb1427c7ffab03d81491c1 to your computer and use it in GitHub Desktop.
add/remove class without jQuery (just Vanilla JS)
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
/** | |
* Remove a CSS class from an HTML element. | |
* @param {HTMLElement} el The HTML element to modify. | |
* @param {string} className The class to remove. | |
* @returns null | |
* @see http://youmightnotneedjquery.com/#remove_class | |
*/ | |
function removeClass(el, className) { | |
if (el.classList) | |
el.classList.remove(className); | |
else | |
el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); | |
} | |
/** | |
* Add a CSS class to an HTML element. | |
* @param {HTMLElement} el The HTML element to modify. | |
* @param {string} className The class to add. | |
* @returns null | |
* @see http://youmightnotneedjquery.com/#add_class | |
*/ | |
function addClass(el, classsName) { | |
if (el.classList) | |
el.classList.add(className); | |
else | |
el.className += ' ' + className; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment