How to Toggle an Element Class in JavaScript ?


Toggling an element class in JavaScript means adding a class to an element if it doesn't have it, and removing it if it already has it. There are multiple ways to achieve this:

  • Using classList.toggle() method: The classList property returns the class name(s) of an element, as a DOMTokenList object. The toggle() method of the DOMTokenList interface removes a given token from the list and returns false. If token doesn't exist it's added and the function returns true.

Example:

<button id="myBtn">Toggle Class</button>
<div id="myDiv">This is a div element</div>
const btn = document.getElementById("myBtn");
const div = document.getElementById("myDiv");

btn.addEventListener("click", function() {
  div.classList.toggle("myClass");
});

In the above example, when the button is clicked, the class "myClass" is added to the div element if it doesn't have it, and removed if it already has it.

  • Using className property: The className property sets or returns the class name(s) of an element. To toggle a class using className, we need to check if the element already has the class. If it does, we remove it, and if it doesn't, we add it.

Example:

<button id="myBtn">Toggle Class</button>
<div id="myDiv" class="myClass">This is a div element</div>
const btn = document.getElementById("myBtn");
const div = document.getElementById("myDiv");

btn.addEventListener("click", function() {
  if (div.className.includes("myClass")) {
    div.className = div.className.replace("myClass", "");
  } else {
    div.className += " myClass";
  }
});

In the above example, when the button is clicked, the class "myClass" is removed from the div element if it has it, and added if it doesn't have it.

  • Using toggleClass() function from a library like jQuery: jQuery is a popular JavaScript library that simplifies HTML document traversing, event handling, and animating. It provides a toggleClass() function that adds or removes one or more classes from the selected elements.

Example:

<button id="myBtn">Toggle Class</button>
<div id="myDiv">This is a div element</div>
const btn = document.getElementById("myBtn");
const div = document.getElementById("myDiv");

btn.addEventListener("click", function() {
  $(div).toggleClass("myClass");
});

In the above example, when the button is clicked, the class "myClass" is added to the div element if it doesn't have it, and removed if it already has it, using the toggleClass() function from jQuery.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.