toggleClass() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:toggleClass

Description

The toggleClass() method toggles between adding and removing one or more class names from the selected elements.

Syntax

$(selector).toggleClass(classname,function(index,currentclass),switch);
ParameterRequire Description
classnameRequired. one or more class names to add or remove.
function(index,currentclass) Optional. function that returns one or more class names to add/remove
switch Optional. A Boolean value specifying if the class should only be added (true), or only be removed (false)

To specify several classes, separate the class names with a space

  • index - the index position of the element in the set
  • currentclass - current class name of selected elements

The following code shows how to Toggle between adding and removing the "main" class name for all <p> elements:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.main {/* www.  j  ava  2  s .co  m*/
    font-size: 120%;
    color: red;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").toggleClass("main");
    });
});
</script>
</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>

Related Tutorials