jQuery Tutorial Tutorials - jQuery .toggleClass() method

jQuery .toggleClass() method

The .toggleClass() method in jQuery is used to Add(if it don't have) /Remove(if it have) the class(es) from the matched elements.

jQuery .toggleClass() method Syntax

$.toggleClass(className)
$.toggleClass(className,state)
$.toggleClass(function[,state])
$.toggleClass([state])
Parameter Type Description
className String One or more class names(separated by spaces)
state Boolean A Boolean value to determine whether the class should be added or removed
funtion(index, oldClassName,state) Function a function returning one or more space-separated class names to be toggled.
index is the position of the element in the set.(based 0)
oldClassName is/are old class name(s).

.toggleClass(className)

example

Toggle the class "selected" from the matched elements.

$("p").toggleClass("selected");

Try now

.toggleClass(className,state)

$( "#foo" ).toggleClass( className, addOrRemove );
is equivalent to:
if ( addOrRemove ) {
$( "#foo" ).addClass( className );
} else {
$( "#foo" ).removeClass( className );
}

example

Add the "highlight" class to every even paragraph.

var count = 0;
$('p').each(function(){
    count++;
    $(this).toggleClass("highlight",count % 2 === 0);
});

Try now

.toggleClass(function[,state])

example

Toggle the class "item-*" from matched elements.

$('ul li').toggleClass(function(index) {
    return "item-" + index;
});

Try now

Date:2019-08-19 16:38:25 From:www.Lautturi.com author:Lautturi