jQuery addClass()

The jQuery addClass() method adds one or more class names to the selected element.

Syntax:

$(selector).addClass(classname,function(index,oldclass))

Classname:

  • Classname is a compulsory parameter of the jQuery addClass() method, as it specifies the class names to be added.

Function:

  • It is an optional parameter.
  • The function parameter is used to return the property’s class names to be added.

Index:

  • The index is an argument passed within the function.
  • It is used to give an index position to an element in the set.

Currentclass:

  • This parameter returns the current class name of the selected element.

Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p:first").addClass("yo");
});
});
</script>
<style>
.yo {
font-size: 250%;
color: red;
}
</style>
</head>
<body>
<h1>Hello!</h1>
<p>How are you?</p>
<p>Nice to see you again.</p>
<button>Click me</button>
</body>
</html>