Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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