Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
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
3.3.
Using Contains() Add() and Remove() methods 
3.4.
HTML
3.5.
Using JQuery’s toggleClass() method
3.6.
HTML
4.
Frequently Asked Questions
4.1.
Q. How to toggle switch using JavaScript?
4.2.
Q. What is the difference between toggle and add class?
4.3.
Q. What is the JavaScript toggle on and off extension?
4.4.
Q. Why do we use toggle class?
4.5.
Q. What are some functions present in the classList property of an HTML element?
4.6.
Q. Why do we need toggling of element class in Javascript?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

How to toggle an element class in JavaScript?

Author Rohit Kumar
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM
toggle JavaScript

Introduction

Hello Ninjas, I hope you are familiar with the uses of class in CSS. In CSS, classes are used so that a group of elements can be given a similar styling, and we don't have to write the same piece of code for styling for every element separately. But what if we want to assign different classes to an element or switch between different classes based on the actions of users so that the element can have different properties based on the user's action? This can be done using the toggle javascript function.

Toggle Javascript

In this article, we will learn about the toggle javascript function. We will discuss this function's uses, syntax, and code implementation. We will also discuss other ways to toggle an element class in JavaScript. So without any delay, let's dive deep into the topic.

What is toggle () in JavaScript?

The toggle Javascript function 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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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

Q. 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.

Q. 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.

Q. 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.

Q. Why do we use toggle class?

The toggleClass() method toggles between adding and removing one or more class names from the selected elements. This method checks each element for the specified class names.

Q. What are some functions present in the classList property of an HTML element?

Some of the functions that are present in the classList property of an HTML element are add(), remove(), length, replace(), item(), etc. Length returns the number of classes added to that element while replace(), replaces the number  

Q. 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.

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-

 

Thanks for reading. I hope you found the blog insightful and that you have understood the use of toggling in javascript.

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMS, and  System Design, etc. as well as some Contests, Test SeriesInterview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

Happy Learning!!

Previous article
Lodash _.matchesProperty() Method
Next article
Lodash _.entries() Method
Live masterclass