jQuery toggleClass()

Introduction

Toggle between adding and removing the "main" class name for all <p> elements:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>/*from  w  w  w.  j  av a2 s  .com*/
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").toggleClass("main");
  });
});
</script>
<style>
.main {
  font-size: 120%;
  color: red;
}
</style>
</head>
<body>

<button>Toggle class "main" for p elements</button>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p><b>Note:</b> Click the button more than once to see the toggle effect.</p>

</body>
</html>

The toggleClass() method adds or removes one or more class names from the selected elements.

The class names are added if missing, and removed if already set.

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

$(selector).toggleClass(classname,function(index,current_class),switch)
Parameter
Optional
Description
classname

Required.

one or more class names to add or remove.
To specify several classes, separate the class names with a space
function(index,current_class)


Optional.


sets a function that returns one or more class names to add/remove
index - the index position of the element in the set
current_class - current class name of selected elements
switch
Optional.
A Boolean value specifying if the class should only be added (true), or only be removed (false)



PreviousNext

Related