• 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 of an Element

Toggle a Class of an Element

Toggle a Class of an Element

To toggle a class of an element, you use the toggle() method of the classList property of the element.

element.classList.toggle(className);

If the element has the className, the toggle() method removes it. If the element doesn’t have the className, the toggle() method adds the className to the classList.

Suppose you have the following element:

<div class="show">Item</div>

The following illustrates how to toggle the show class of the <div> element:

const div = document.querySelector('div');
div.classList.toggle('show');

Source

https://www.javascripttutorial.net/toggle-a-class-of-an-element/

CSS

Related Snippets:

  • Find all matching elements on a page with document.querySelectorAll()
  • Text Sections
  • Resize the width of a text box to fit its content automatically
  • Add a Class to an Element

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