jQuery toggleClass() Method

jQuery | toggleClass() Method: Learn about the jQuery toggleClass() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 16, 2022

toggleClass() Method

Generally, a CSS class is declared when the HTML of the page is written down. At that time only the classes are specified for the elements. During that time a lot of CSS classes are declared for an element. There might be a situation when you want to remove and add a class based on some dynamic events. This can be achieved by using jQuery's method – toggleClass().

The toggleClass() method in jQuery helps to toggle between the classes. This means that if the class specified in this method is not contained by the selected element, then it will add the class to it. On the other hand, if the class is present then this method will remove it from the element. This way it switches between the respective class.

toggleClass() Method Syntax


Along with the class name as its parameter, it also takes an optional parameter – switch. Switch can be defined as true or false. This follows only one event, i.e., it only allows you to either add or remove the specified class. By default, the switch is always set as – true.

Now, the following example explains the implementation of the toggleClass() method in jQuery. When the button is clicked, it triggers the method which further switches the classes for the element.

jQuery toggleClass() Method Example

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
      font-size: larger;
      font-weight: bolder;
      color: green;
      font-size: larger;
      font-weight: bolder;
    <h2>jQuery - ToggleClass</h2>
    <p>Click the button to toggle between the classes.</p>
    <div>This is SENTENCE ONE</div>
    <div>This is SENCTENCE TWO</div>
    <p class="blue">This is SENTENCE THREE</p>
    <h3 style="color:crimson ;"></h3>
  <script type="text/javascript">


Example 1: jQuery toggleClass() Method

All jQuery Examples

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.