Table of contents
1.
Introduction
2.
What is toggle() in JavaScript?
2.1.
1. classList
2.2.
HTML
2.3.
2. contains()
2.4.
HTML
2.5.
3. add()
2.6.
HTML
2.7.
4. remove()
2.8.
HTML
2.9.
5. toggle()
2.10.
HTML
3.
Different Ways to Toggle an Element Class in Javascript
3.1.
Using Toggle() Method:
3.2.
HTML
4.
Using Contains() Add() and Remove() methods 
4.1.
HTML
5.
Using JQuery’s toggleClass() method
5.1.
HTML
6.
Frequently Asked Questions
6.1.
How to toggle switch using JavaScript?
6.2.
What is the difference between toggle and add class?
6.3.
What is the JavaScript toggle on and off extension?
6.4.
Why do we need toggling of element class in Javascript?
6.5.
How to remove toggle class in JavaScript?
6.6.
How do you toggle values in JavaScript?
7.
Conclusion
Last Updated: Jan 7, 2025
Easy

How to toggle an element class in JavaScript?

Author Rohit Kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?
toggle JavaScript

Introduction

Toggling a class in JavaScript is a simple yet powerful way to dynamically update an element's appearance or behavior. This technique allows you to add or remove classes based on specific conditions, enhancing interactivity on your web page. 

Toggle Javascript

In this article, we will learn about the toggle javascript function. We will discuss this function's uses, syntax, and code implementation.

What is toggle() in JavaScript?

The toggle() function in Javascript adds a class to an element if that class is not already associated with that element. And if the class is already associated with that element, then that class is removed from that element.

We can think of a toggle as a switch used to turn a class on and off for the element it is used for. If the class is on, that class is associated with the element, then it is turned off, which means it is removed from that element. This switching action is done dynamically when certain events occur (onClick, etc.).

Another way to do the toggling of an element class in javascript is by using different HTML elements properties such as classList(), contains(), add(), and remove().

Furthermore, JavaScript offers significant DOM manipulation capabilities, allowing developers to easily create interactive and responsive online apps. Developers may use these features to dynamically update and modify web page content, handle user interactions, perform real-time data updates, and seamlessly incorporate multimedia elements, all of which improve the overall user experience.

Let's see what they do before using them to perform toggle in javascript. 

1. classList

It returns the names of the CSS classes associated with an HTML element DOMTokenList object. It just reads the name of classes and cannot modify the class names; hence it is also an example of a read-only DOM method. 

Example-

  • HTML

HTML

<!DOCTYPE html>
<html lang="en">


<head>
   <meta charset="UTF-8">
   <title>Coding Ninja | Toggle JavaScript</title>
</head>


<body>
   <h1 class="class1 class2">Toggle JavaScript</h1>
   <script>
       const h1 = document.querySelector("h1");
       console.log("Initial class names: ", h1.classList);
   </script>
</body>
</html>

 

Output-

Code output

Explanation-

We are defining an h1 element in the body of our HTML page. Then we print the name of the classes on the console.

2. contains()

It checks whether the given class is present in a given element. It returns a boolean value based on the result.

Example-

  • HTML

HTML

<!DOCTYPE html>
<html lang="en">


<head>
   <meta charset="UTF-8">
   <title>Coding Ninja | Toggle JavaScript</title>
</head>


<body>
   <h1 class="class1 class2">Toggle JavaScript</h1>
   <script>
       const h1 = document.querySelector("h1");
       console.log(h1.classList.contains(“class1”));
       console.log(h1.classList.contains(“class3”));
   </script>
</body>
</html>

 

Output-

Code output

 

Explanation-

We are defining an h1 element in the body of our HTML page and have added "class1" and "class2" to it. In the script tag, we check if the element contains "class1" and "class3". It returns true for "class1" and false for "class3".

3. add()

It is used to add a given class to a given element without affecting any classes that were already there in that element. If the class we are adding is already present, it won't make any changes.

Example-

  • HTML

HTML

<!DOCTYPE html>
<html lang="en">


<head>
   <meta charset="UTF-8">
   <title>Coding Ninja | Toggle JavaScript</title>
</head>


<body>
   <h1 class="class1 class2">Toggle JavaScript</h1>
   <script>
       const h1 = document.querySelector("h1");
       console.log("List of class before adding the class 3")
       console.log(h1.classList);
       h1.classList.add("class3");
       console.log("List of class after adding the class 3")
       console.log(h1.classList);
   </script>
</body>
</html>

 

Output-

Code output

Explanation-

We have defined an h1 element and added "class1" and "class2" to it initially. We then add another class, "class3," to this element and then console the list of classes before adding the "class3" and after adding the "class3".

4. remove()

As the name suggests, it removes a given class from a given element without affecting existing classes. If the class that we are removing was already not present in the element, then it won't make any changes, and neither will it throw any error.

Example-

  • HTML

HTML

<!DOCTYPE html>
<html lang="en">


<head>
   <meta charset="UTF-8">
   <title>Coding Ninja | Toggle JavaScript</title>
</head>


<body>
   <h1 class="class1 class2 class3">Toggle JavaScript</h1>
   <script>
       const h1 = document.querySelector("h1");
       console.log("List of class before removing the class 1")
       console.log(h1.classList);
       h1.classList.remove("class1");
       console.log("List of class after removing the class 1")
       console.log(h1.classList);
   </script>
</body>
</html>

 

Output-

Code output

 

Explanation-

We have defined an h1 element and added "class1", "class2," and "class3" to it initially. We then remove the class "class1" from this element and then console the list of classes before removing the "class1" and after removing the "class1".We can see that "class1" has been successfully removed.

5. toggle()

Toggle() is a JavaScript function for changing the state of a DOM element. It's frequently used to toggle visibility, class names, or styles, making it a useful tool for interactive web development.

Example-

  • HTML

HTML

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
box-sizing: border-box;
}
</style>
</head>
<body>

<p>Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is a DIV element.
</div>

<script>
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.toggle("mystyle");
}
</script>

</body>
</html>

Output:

Using toggle() in JS

Description-

This HTML code generates a responsive web page with a button that, when pressed, toggles the "mystyle" class on a div> element. The "mystyle" class alters the div>'s appearance by modifying its width, padding, background color, font size, and text color. It shows how to use JavaScript to toggle a simple CSS class.

Different Ways to Toggle an Element Class in Javascript

Using Toggle() Method:

This is an inbuilt javascript function that helps us to switch between two classes. And as discussed, it works similarly to an electric switch. Suppose the element has the class added to it initially, so when we use the toggle function, the class will be removed from that element. Suppose we will again use the toggle, and this time, the class was not already added to the element; then the class will be added to it.

Syntax:

element.classList.toggle('classOne');

 

Example-

  • HTML

HTML

<!DOCTYPE html>
<html lang="en">


<head>
   <meta charset="UTF-8">
   <title>Coding Ninja | Toggle JavaScript</title>
</head>


<body>
   <h1 class="class1 class2 class3">Toggle JavaScript</h1>
   <script>
       const h1 = document.querySelector("h1");
       console.log("List of class before toggling class 1 and class 4")
       console.log(h1.classList);
       h1.classList.toggle("class1");
       h1.classList.toggle("class4");
       console.log("List of class after toggling class 1 and class 4")
       console.log(h1.classList);
   </script>
</body>
</html>

 

Output-

Code output

 

Explanation-

We have defined an h1 element and added "class1", "class2," and "class3" to it initially. We then toggle the class "class4" and "class1" from this element and then console the list of classes before and after toggling the classes. We can see that "class1" has been removed after toggling since it was already added to the h1 element, while "class4" has been added to the h1 element.

Using Contains() Add() and Remove() methods 

Contains(), Add(), and Remove() methods can be used along with the classList attribute of the HTML element to toggle an Element Class in Javascript. To do so, we will first check with the help of Contains method whether the class that we want to toggle is present or not in the element. If the class is preset, we will remove it using the Remove method, and if the class is absent from that element, we will add it to that element using the Add method. 

Example-

  • HTML

HTML

<!DOCTYPE html>
<html lang="en">


<head>
   <meta charset="UTF-8">
   <title>Coding Ninja | Toggle JavaScript</title>
</head>


<body>
   <h1 class="class1 class2 class3">Toggle JavaScript</h1>
   <script>
       const h1 = document.querySelector("h1");
       console.log("List of class before toggling the class 1")
       console.log(h1.classList);
       if(h1.classList.contains("class1")){
           h1.classList.remove("class1");
       }else{
           h1.classList.add("class1");
       }
       console.log("List of class after toggling class 1")
       console.log(h1.classList);
   </script>
</body>
</html>

 

Output-

Code output

 

Explanation- 

We have defined an h1 element and added "class1", "class2" and "class3" to it initially. We then toggle the class "class1" from this element and console the list of classes before and after toggling the class. To toggle, we will first check if the "class1" was initially added to the h1 element or not using contains(). If it exists, we remove it; otherwise, we will add it. In the example, the" class1" was already added to the h1 element; hence it got removed.

Using JQuery’s toggleClass() method

To add or remove one or more classes from the specified components, use the jQuery toggleCLass() method. This method allows you to add and remove one or more class names. It looks for the supplied class names in each element. If the class name is already set, it is removed; otherwise, it is added.

Example-

  • HTML

HTML

<!DOCTYPE html>  
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggleClass("main");
});
});
</script>
<style>
.main {
font-size: 150%;
color: red;
}
</style>
</head>
<body>
<button>Toggle class "main" for p elements</button>
<p>Hello! Welcome Back Ninja</p>
<p>This is popular tutorial website.</p>
<p><b>Note:</b> Click repeatedly on the button to see the toggle effect.</p>
</body>
</html>

Output-

Using JQuery’s toggleClass() method

Explanation-

This HTML code includes a jQuery script that toggles the "main" class on p> components when a button is clicked. The "main" class alters the text size and color. Clicking the button several times displays the toggle effect, which makes the text larger and red before returning to normal.

Frequently Asked Questions

How to toggle switch using JavaScript?

The toggle element is given a click event listener by the JavaScript code. When the toggle switch is pressed, the event listener uses the classList. toggle() function to toggle the on class on the toggle element.

What is the difference between toggle and add class?

The addClass ensures that a particular class is present on an element, while the oggleClass adds the class if it isn't there and removes it if it is.

What is the JavaScript toggle on and off extension?

The "JavaScript Toggle On and Off" plugin offers a dependable way to toggle JavaScript execution. You can still execute JavaScript after installation. Click the action button whenever you need to block.

Why do we need toggling of element class in Javascript?

Toggle is very important in javascript because it helps us to build components such as an accordion, hamburger menu, and like/dislike feature. It also helps us to add complex features which were otherwise impossible without toggling element classes in javascript.

How to remove toggle class in JavaScript?

To remove a toggled class in JavaScript, use classList.remove('className') on the target element. If you’ve been using classList.toggle(), this approach ensures the specified class is removed, regardless of its state.

How do you toggle values in JavaScript?

To toggle values in JavaScript, use conditional statements like if-else or the ternary operator. For example, value = (value === 'on') ? 'off' : 'on' switches between two values based on the current state.

Conclusion

Congrats, Ninja!! You've learned about the toggle javascript function and also what toggling of classes means in javascript. You've also learned how to toggle different element classes in javascript. You also learned the use of different functions such as add, remove, contain, and toggle. 

We also added FAQs related to toggling in Javascript.

Recommended Reading-

Live masterclass