Toggle class of HTML element

OSCC · JavaScript, Browser · Oct 22, 2020

Toggles a class for an HTML element.

  • Use Element.classList and DOMTokenList.toggle() to toggle the specified class for the element.
const toggleClass = (el, className) => el.classList.toggle(className);
toggleClass(document.querySelector('p.special'), 'special');
// The paragraph will not have the 'special' class anymore

Recommended snippets