• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / CSS / Toggle a class for an HTML element

Toggle a class for an HTML element

Toggle a class for an HTML element

toggleClass 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);

// EXAMPLE
toggleClass(document.querySelector('p.special'), 'special');
// The paragraph will not have the 'special' class anymore

Source

https://www.30secondsofcode.org/js/s/toggle-class

CSS

Related Snippets:

  • Replace a Class of an Element
  • Get and Set Classes On An Element
  • Get all of an element’s parent elements up the DOM tree
  • Add, remove, toggle, and check for the presence of a class

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers