JavaScript Tutorials

4 Ways To Toggle Class On Element In JavaScript

Raja Tamil
Javascript

Learn how to toggle one or more CSS classes in an HTML element using JavaScript.

  1. Toggle A Class On Click Using classList.toggle()
  2. Toggle Between Two Classes On An Element
  3. Toggle A Class On Multiple Elements
  4. Toggle A Class Between Multiple Elements

1. Toggle A Class On Click Using classList.toggle()

Here is a simple button HTML element with an id button.

<button id="button">Button</button>

Here is the simple style for the button.

body {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color:grey;
}

button {
    padding: 10px;
    font-size: 1.1em;
    background: white;
    color: black;
    border: none;
    border-radius: 10px;
    border: 1px solid rgba(0, 0, 0, 0.2);
    cursor: pointer;
}

.active {
  background:#32bacf;
}

Next, toggle the .active CSS class when a button is clicked.

Luckily, the classList API has a method called toggle() that does exactly that.

Get a DOM reference of the button element using the getElementById() method on the document object.

Attach a click event to the button element with the callback function buttonPressed.

const button = document.getElementById("button"); 
const buttonPressed = (e) => {
  e.target.classList.toggle("active");
}
button.addEventListener("click", buttonPressed);

Inside the callback function, get the clicked button element using the event object (e) that is passed into the function.

Call the toggle() method on the button element which is e.target.

Finally, pass the class name that you want to toggle as an argument of the toggle() method.

In this case .active class.

Try it now

See the Pen Toggle Class Javascript #1 On Button Click by SoftAuthor (@softauthor) on CodePen.

2. Toggle Between Two Classes On An Element

Let’s toggle between two classes on an element.

When a button is pressed, the .green class will be added to the element and .red class will be removed and vice-versa.

Here is the simple button element with an id button, as well as the class .red

As you can see, by default, the button has the red class.

<button id="button" class="red">OFF</button>

Here are the two CSS classes: .red and .green.

.red {
  background:red;
  color:white;
}

.green {
  background:green;
  color:white;
}

Get a DOM reference of the button using the getElementById() method on the document object.

Attach a click event to the button with the callback function buttonPressed.

Use the classList.toggle() method to toggle the green class on the button element.

const button = document.getElementById("button"); 
const buttonPressed = (e) => {
  e.target.classList.toggle("green");
}
button.addEventListener("click", buttonPressed);

At this stage, the .green class will be toggled when the button is pressed but the .red class will still be present.

But you may wonder…

Why the button changed to green color when both .green and .red classes presend on the element?

The reason is that the .green CSS rule is declared after the .red CSS rule in the style sheet.

But what I want is to get rid of the .red class when the .green class is added to the button element and vice-versa.

This way I can make sure that the button element has either a .green or .red class when the button is pressed.

And I do not have to worry about the order of the CSS rules that are declared inside the style sheet.

To do that, toggle both classes using classList.toggle()

const button = document.getElementById("button"); 
const buttonPressed = (e) => {
  e.target.classList.toggle("green");
  e.target.classList.toggle("red");
}
button.addEventListener("click", buttonPressed);

Let’s also change the button text to ON when the .green class is added and OFF when the .red class is added.

const button = document.getElementById("button"); 
const buttonPressed = (e) => {
  e.target.classList.toggle("green");
  e.target.classList.toggle("red");
  e.target.innerText = e.target.innerText.trim() === "OFF" ? "ON" : "OFF";

}
button.addEventListener("click", buttonPressed);

Try it out

See the Pen Toggle Class Javascript #2 Toggle Multiple Classes Of An Element by SoftAuthor (@softauthor) on CodePen.

3. Toggle A Class On Multiple Elements

Learn how to toggle a class on multiple elements at once when a button is pressed.

Here is the button element with an id button and it has the text Apply Red.

There are five div elements with the class name box in them.

<button id="button">Apply Red</button>

<div class="box">box <br>1</div>
<div class="box">box <br>2</div>
<div class="box">box <br>3</div>
<div class="box">box <br>4</div>
<div class="box">box <br>5</div>

Now let’s change the background color of all boxes to red using the .red class when the button is pressed.

Get a DOM reference of the button element using the getElementById() method on the document object.

Similarly, get DOM references of all the div elements using the getElementsByClassName() method on the document object.

Attach a click event to the button element with the callback function buttonPressed.

const button = document.getElementById("button"); 
const boxes = document.getElementsByClassName("box");
const buttonPressed = () => {
  for(const box of boxes) {
    box.classList.toggle("red");
  }
}
button.addEventListener("click", buttonPressed);

Inside the callback function, loop through the boxes HTMLCollection which is an array-type object.

Define for..of loop and create a box constant in the loop header which will hold a div element on each iteration.

Finally, toggle the .red class using classList.toggle() inside the loop.

Try it out

See the Pen Toggle Class Javascript #3 Toggle Class Multiple Elements by SoftAuthor (@softauthor) on CodePen.

4. Toggle A Class Between Multiple Elements

Now, let’s toggle the .active class between multiple elements depending on which button is clicked, which is one of the common functionalities that you see on websites/web apps.

Here is the wrapper div with an id button-group, and it has four buttons in it.

<div id="button-group">
   <button>Debit</button>
   <button>Credit</button>
   <button>Paypal</button>
   <button>E-transfer</button>
</div>

Now let’s add the .active class to the clicked button and remove it from the previously clicked button.

There are multiple ways to do that.

Here is one of the recommended approaches without using a loop.

Get a DOM reference of the button-group element using the getElementById() method on the document object.

Assign the button group element object to a constant called buttonGroup.

Next, declare prevButton and set its value to null.

The prevButton will hold the button element that is previously clicked.

Attach a click event to the buttonGroup element with the callback function buttonPressed.

const buttonGroup = document.getElementById("button-group"); 
let prevButton = null;

const buttonPressed = (e) => {
  if(e.target.nodeName === 'BUTTON') {
    e.target.classList.add('active'); // Add .active CSS Class

    if(prevButton !== null) {
      prevButton.classList.remove('active');  // Remove .active CSS Class
    }

    prevButton = e.target;
  }
}
buttonGroup.addEventListener("click", buttonPressed);

Inside the callback function, check to see if the clicked element is a button using the event object that is passed into the function.

Then add the active class using the add() method on the currently clicked button, which is e.target.

After that, check to see if the prevButton is not null, meaning a user has already clicked it before.

In that case, remove the .active class from the previously clicked button.

Finally, assign the currently clicked button to the prevButton.

Try it out

See the Pen Toggle Class Javascript #4 Toggle Class Only Clicked Element by SoftAuthor (@softauthor) on CodePen.

You may also like: