W3Schools.com

jQuery HTML toggleClass() Method

jQuery HTML Methods jQuery HTML Methods

Example

Toggle between adding and removing the "main" class for p elements:

$("button").click(function(){
  $("p").toggleClass("main");
});

Try it yourself »

Definition and Usage

The toggleClass() method toggles between adding and removing one or more classes for the selected elements.

This method checks each element for the specified classes. The classes are added if missing, and removed if already set - This creates a toggle effect.

However, by using the "switch" parameter, you can specify to only remove, or only add a class.


Syntax

$(selector).toggleClass(class,switch)

Parameter Description
class Required. Specifies one or more class names to add or remove.

To specify several classes, separate the class names with a space.
switch Optional. A Boolean value specifying if the class should be added (true), or removed (false).


Toggle Classes Using a Function

Using a function to specify which classes should be toggled for the selected elements.

Syntax

$(selector).toggleClass(function(index,class),switch)

Try it yourself »

Parameter Description
function(index,class) Specifies a function that returns one or more class names to add/remove.
  • index - Optional. Receives the index position of the selector
  • class - Optional. Receives the current class of the selector
switch Optional. A Boolean value specifying if the class should be added (true), or removed (false).


Examples

Try it Yourself - Examples

Toggle between adding and removing a class
How to use the toggleClass() method to toggle between adding and removing a class.

Using the switch parameter
How to use the switch parameter to only add or remove a class.


jQuery HTML Methods jQuery HTML Methods


WEB HOSTING
Best Web Hosting
PHP MySQL Hosting
Best Hosting Coupons
UK Reseller Hosting
Cloud Hosting
Top Web Hosting
$3.98 Unlimited Hosting
Premium Website Design
WEB BUILDING
XML Editor - Free Trial!
FREE Website BUILDER
Best Website Templates Top CSS Templates
CREATE HTML Websites
EASY WEBSITE BUILDER
W3SCHOOLS EXAMS
Get Certified in:
HTML, CSS, JavaScript, XML, PHP, and ASP
W3SCHOOLS BOOKS
New Books:
HTML, CSS
JavaScript, and Ajax
STATISTICS
Browser Statistics
Browser OS
Browser Display
SHARE THIS PAGE