addClass() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:addClass

Description

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

Syntax

$(selector).addClass(classname, function(index,currentclass));
ParameterRequireDescription
classnameRequired. one or more class names to be added
function(index,currentclass) Optional. a function that returns one or more class names to be added
  • index - the index position of the element in the set
  • currentclass - the current class name of the selected element

The following code shows how to Add a class name to the first <p> element:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.intro {//  w  w  w . ja  va 2 s.  co m
    font-size: 150%;
    color: blue;

}
</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:first").addClass("intro");
    });
});
</script>
</head>
<body>

<button>Add a class name to the first p element</button>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>This is another paragraph.</p>
<p>This is another paragraph.</p>

</body>
</html>

Related Tutorials