Open In App

How to Toggle an Element Class in JavaScript ?

Last Updated : 20 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In JavaScript, toggling an element class refers to the process of dynamically adding or removing a CSS class from an HTML element. This allows developers to easily change an element’s appearance or behavior in response to user actions, such as clicks or events.

These are the following methods for toggling an element Class:

Method 1: Using the toggle() method

The toggle() method in JavaScript’s classList object adds a specified class to an element if it’s not present, and removes it if it is. This allows for easy, dynamic switching of styles or behaviors in response to user interactions or events.

Example: In this example we toggles a CSS class on a paragraph element. When the button is clicked, it dynamically adds or removes the “paragraphClass,” changing the font size and color of the text.

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

<head>
    <meta charset="UTF-8">
    <title>Geeks for Geeks</title>
    <style>
        .paragraphClass {
            font-size: 30px;
            color: red;
        }

        #Button {
            margin-top: 15px;
        }
    </style>

    <script>
        function myFunc() {
            let para = document.getElementById("p");
            para.classList.toggle("paragraphClass");
        }
    </script>
</head>

<body>
    <p id="p">
        Click on the button to toggle
        between the class to see the
        effects
    </p>

    <button id="Button" onclick="myFunc()">
        Click Me
    </button>
</body>

</html>

Output:

How to Toggle an Element Class in JavaScript ?

How to Toggle an Element Class in JavaScript ?

Method 2: Using contains(), add() and remove() Method

In this example we use classList.contains() to check if an element has a specific class, classList.add() to add a class, and classList.remove() to remove it. These methods offer fine control over element class manipulation dynamically.

Example: In this example we toggles a CSS class using contains(), add(), and remove(). It checks if the paragraph has a specific class, removes it if present, or adds it otherwise on button click.

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

<head>
    <meta charset="UTF-8">
    <title>Geeks for Geeks</title>
    <style>
        .paragraphClass {
            font-size: 30px;
            color: red;
        }

        #Button {
            margin-top: 15px;
        }
    </style>

    <script>
        function myFunc() {
            let para = document.getElementById("p");

            if (para.classList.contains("paragraphClass")) {
                para.classList.remove("paragraphClass");
            }
            else {
                para.classList.add("paragraphClass");
            }
        }
    </script>
</head>

<body>
    <p id="p">
        Click on the button to toggle
        between the class to see the
        effects
    </p>

    <button id="Button" onclick="myFunc()">
        Click Me
    </button>
</body>

</html>

Output: 

How to Toggle an Element Class in JavaScript ?

How to Toggle an Element Class in JavaScript ?


Master JavaScript with our full Javascript - Beginner to Advanced online course! From basics to advanced techniques, build interactive websites and earn a certification. Take the Three 90 Challenge—complete 90% in 90 days for a 90% refund. Start now and unlock your JavaScript potential!


Next Article

Similar Reads

Toggle class by adding the class name when element is clicked and remove when clicked outside
In this article, the task is to toggle a CSS class when clicked on that element and remove that particular class when clicked outside that element, that is, anywhere else in the HTML document. Approach: This can be easily accomplished with the help of JavaScript by following the steps below: We will first select the element on which the class has t
2 min read
How to toggle CSS class on an element dynamically using ReactJS ?
Sometimes developers need to toggle CSS class on an element dynamically using ReactJS due to the DOM events and modifications after the User Interaction or change in data from API. For example, when the user clicks on one element we can change the styling for any particular element by toggling the CSS class. Prerequisites:NPM & Node.jsReact JST
4 min read
How to Toggle between Hiding and Showing an Element using JavaScript ?
Toggle between hiding and showing an element using JavaScript provides the feature of efficient space usage by allowing users to hide content sections they may not need to minimize distractions, leading to a cleaner and more organized layout. Syntaxif (paragraph.style.display === 'none') { paragraph.style.display = "block";}else { paragraph.style.d
3 min read
How to toggle class using AngularJS ?
In this article, we will toggle the class of an element with the help of AngularJS. The toggling of the class can be done in 2 ways, i.e., either specifying the value to 0 or 1, depending upon the condition satisfied, by initially defining the value as 0, or depending on the boolean value, i.e., true or false, with satisfying the required condition
3 min read
How to Toggle a Class in Vue.js ?
In this article, we will use Vue.js component with a simple HTML template containing <div> and button elements. The goal is to toggle the presence of a CSS class on the <div> element when the button is clicked. By understanding the concepts of data binding, conditional rendering, and event handling in Vue.js, you'll be able to create mo
3 min read
How to Double click on a div element to toggle background color in jQuery ?
In this article, we will see how to make a double click event on a paragraph element to toggle background color in jQuery. To toggle the background color of a div element on double-click, toggleClass() method is used. The toggleClass() method is used to toggle or change the class which attached with selected element. Syntax: $(selector).dblclick(fu
1 min read
How to set, clear and toggle a single bit of a number in JavaScript?
Given a JavaScript number and the task is to set, clear and toggle a single bit of any number. Here are few approaches discussed with the help of JavaScript. Setting the bit: Get the position of the bit to be set(starts from right, first bit is at 0 position), Ex. (bitSet = 3) Get the mask by mask = 1 << setBit, this mask is helpful in settin
3 min read
How to Toggle Password Visibility in JavaScript ?
In this article we will discuss how to toggle password visibility in JavaScript we will also use HTML and CSS in order to create a password visibility toggler for our webpage. Approach: The basic approach towards making password visibility toggler will be quite simple, we will use a button and write a javascript function and call that on the button
4 min read
Create a Toggle Profile Card Details using HTML CSS and JavaScript
In this article, we will develop an interactive Toggle Profile Card Details application using HTML, CSS, and JavaScript Language. In this application, we have a Card Component with the user's details like their profile picture and Name. There is a toggle button, and when the button is clicked, the detailed information of the user will be displayed
3 min read
Build a responsive Burger Website with Toggle Dark Mode in Tailwind CSS & JavaScript
Burger Website is easy to use and designed with Tailwind CSS and JavaScript. It adjusts smoothly to different screens and has a dark mode option. It's perfect for veggie burger lovers, making it easy to browse and order anytime, anywhere. With Tailwind CSS for styling and JavaScript for interactivity, it provides a fun experience.PreviewPrerequisit
10 min read
  翻译: