Skip to content

Instantly share code, notes, and snippets.

@techieshark
Created May 24, 2018 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techieshark/778825d935bb1427c7ffab03d81491c1 to your computer and use it in GitHub Desktop.
Save techieshark/778825d935bb1427c7ffab03d81491c1 to your computer and use it in GitHub Desktop.
add/remove class without jQuery (just Vanilla JS)
/**
* 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