SoFunction
Updated on 2025-02-28

Example of usage of addClass method in jQuery

This article describes the usage of addClass() method in jQuery. Share it for your reference. The specific analysis is as follows:

This method adds one or more classes to the matching element.
This method has multiple syntax forms.

Syntax Structure 1:

Adds the specified class name to the matching element. If you want to add multiple class names at once, they should be separated by spaces.

Copy the codeThe code is as follows:
$(selector).addClass(class)

Parameter list:

parameter describe
class Define the name of the added class

Example code:

Copy the codeThe code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="https:///" />
<title>addClass function-I</title>
<style type="text/css">
div{
  height:200px;
  width:200px;
}
.border{
  border:1px solid red;
}
.reset{
  font-size:20px;
  color:green;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8."></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#btn").click(function(){
    $("div").addClass("border reset");
  })
})
</script>
</head>
<body>
<div>I welcome you</div>
<button >Click to view the effect</button>
</body>
</html>

The above code can add two classes to the div, which can set the border and font style of the div.

Syntax Structure Two:

Take the return value of the function as the class name to be added.

Copy the codeThe code is as follows:
$(selector).addClass(function(index,oldclass))

Parameter list:

parameter describe
function(index,oldclass) Function definition returns one or more class names that need to be added.
index - optional, accepts the index position of the selector.
oldclass- Optional, accepts the current class name of the selector.

Example code:

Copy the codeThe code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="https:///" />
<title>addClass() function-I</title>
<style type="text/css">
div{
  height:200px;
  width:200px;
}
.border{
  border:1px solid red;
}
.reset{
  font-size:20px;
  color:green;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8."></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#btn").click(function(){
    $("div").addClass(function(){
      return "border reset";
    })
  })
})
</script>
</head>
<body>
<div>I welcome you</div>
<button >Click to view the effect</button>
</body>
</html>

The above code has the same function as the first instance, except that the class to be added returns the value through the function.

I hope this article will be helpful to everyone's jQuery programming.