Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

jquery
toggle
communitycreator

What is the toggleClass() method in jQuery?

Shubham Singh Kshatriya

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The toggleClass() method is used to toggle, that is, add or remove classes from a selected element.

If the given class is not present in the selected element, then the toggleClass() method will add that class to the element, and if the given class is already present in the selected element, then the toggleClass() method will remove that class from the element.

Syntax

$(selector).toggleClass(className,function(index,currentClass),switch);

Parameters

This method accepts the following parameters.

  • className: The class name(s) that will be added or removed. It is a required parameter.
  • function: An optional function that will return the class name(s) to be added or removed. It accepts the following two parameters.
    • index: It will return the index of the element present in the set.
    • currentClass: It will return the current class name of the selected element.
  • switch: An optional boolean that specifies whether the given class should be added or removed. If true, the given class will be added, and vice-versa.

Example

In the code snippet below, we see an example of the toggleClass() method.

Explanation

In the JavaScript tab:

  • Line 4: We attach the click() method on the button.
  • Line 6: We use the toggleClass() method to toggle class change when the button is clicked.

Output

When the button is clicked, the class change will be toggled. Therefore, the color of the text will change.

RELATED TAGS

jquery
toggle
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring