jQuery addClass() Method - CodingTag
×


jQuery addClass()

1071

  • This jQuery method is used to attach one or more class to the selected HTML elements.
  • This method only adds the given class to the element without removing the existing classes.
  • In case of more than one class, they should be separated by comma(,).

Related Topics:

jQuery position
jQuery offset

jQuery addClass

Syntax:

$(selector).addClass(class_name,function(index,currentclass));

Parameter description:

  • class_name: This parameter represents the name of class or classes to be attach to the selected element. It is mandatory.
  • function(index, currentclass): This represents a user defined function which returns the names of one or more class to attach to the selected HTML element.
  • index: This parameter is used to get the index position of the element in the set.
  • currentclass: This parameter is used to return the current class name of the selected element.

Example:

In this example we attach the para class to all paragraphs and head class to all headings.

<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
.para{
background:yellow;
padding:10px;
font-size:20px;
}
.head{
background:pink;
padding:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").addClass("para");
$("h3").addClass("head");
});
;

});
</script>
</head>
<body>
<h2> jQuery addClass() Method Example </h2>
<h3> This is heading 1 </h3>
<h3> This is heading 2 </h3>
<p> This is paragraph 1 </p>
<p> This is paragraph 2 </p>
<button> Click me! </button>
</body>
</html>

Output:

When you click the button,


Example 2

In this example we attach para0 and para1 classes to the given paragraphs by using a function.

<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
.para0{
background:yellow;
padding:10px;

}
.para1{
background:pink;
padding:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").addClass(function(x){
return "para" + x;
});
});
;

});
</script>
</head>
<body>

<h2> jQuery addClass() Method Example </h2>
<p> This is paragraph 1 </p>
<p> This is paragraph 2 </p>
<button> Click me! </button>
</body>
</html>

Output:

When you click the button,



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments