jQuery toggleClass() attribute

The jQuery toggleClass() method is used to add or remove one or more class names from the selected elements. It adds the class name, if the class name is missing from the selected element and it removes the class name if the class name already exists from the selected element.

Syntax of toggleClass() attribute

$(selector).toggleClass(classname) 

The selector is the element from which class to be added/removed. The 'classname' is the required parameter. It specifies one or more class names to add/remove. To add/remove multiple classes, separate each class names with a space.

Example

<style>
.cls { 
font-size: 22px;
}
.txt {
font-style: italic; 
}
.clr { 
color: blue;
}
</style>

<p id="demo" class="cls txt"> 
Some content goes here.
Some content goes here.
Some content goes here.
</p>

<script>
$(document).ready(function(){
$("p#demo").toggleClass("cls txt clr");
});
</script>

Output of the above code

Some content goes here.
Some content goes here.
Some content goes here.

In the above example, "cls" and "txt" classes are already existing and "clr" class is not found in the paragraph element. After running the toggleClass attribute, "cls" and "txt" classes are removed and "clr" class is added in the paragraph element.



Read more articles


General Knowledge



Learn Popular Language