addClass()

The addclass() method is used to add one or more class name to the selected element. This method is used only to add one or more class names to the class attributes not to remove the existing class attributes.

If you want to add more than one class separate the class names with spaces.

Syntax:

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

Parameters of jQuery addClass() method

Parameter Description
Classname It is a mandatory parameter. It specifies one or more class names which you want to add.
Function (index, currentclass) It is an optional parameter. It specifies a function that returns one or more class names to be added.
  • Index: It is used to provide the index position of the element in the set.
  • Currentclass: It is used to return the current class name of the selected element.

Example of jQuery addClass() method

Let?s take an example to demonstrate the effect of jQuery addclass() method:

snippet
<!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("intro");
    });
});
</script>
<style>
.intro {
    font-size: 200%;
    color: red;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Add a class name to the first p element</button>
</body>
</html>
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +