Latest web development tutorials

jQuery toggleClass () method

jQuery HTML / CSS Methods jQuery HTML / CSS Methods

Examples

To add and remove all <p> elements in the "main" class switching:

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

try it"

Definition and Usage

toggleClass () method to add and remove the selected element to switch one or more classes.

This method checks each element of the specified class. If the class does not exist, add, delete it if you have set. This is called switching effect.

However, by using the "switch" parameter, you can only add or delete provisions only class.


grammar

$(selector).toggleClass(classname,function(index,currentclass),switch)

参数 描述
classname 必需。规定添加或移除的一个或多个类名。如需规定若干个类,请使用空格分隔类名。
function(index,currentclass) 可选。规定返回需要添加/删除的一个或多个类名的函数。
  • index- 返回集合中元素的 index 位置。
  • currentclass- 返回被选元素的当前类名。
switch 可选。布尔值,规定是否仅仅添加(true)或移除(false)类。


Examples

More examples

Add and remove classes to switch
How toggleClass () method to switch to add and remove classes.

Use the function to switch class
Use the function to which the provisions of the current element required to switch the class name.

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


jQuery HTML / CSS Methods jQuery HTML / CSS Methods