How Can I Use AddClass Method In JQuery With Example

admin_img Posted By Bajarangi soft , Posted On 14-10-2020

In Jquery addClass() Adds one or more classes to the selected elements, So Today we discuss how to use addclass method in jquery

How Can I Use AddClass Method In JQuery With Example

Step 1:Create index.html file and implement below code

<h1>Heading 1</h1>
<h2>Heading 2</h2>

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

<div>This is some important text!</div><br>

<button class="btn btn-primary">Add classes to elements</button>


Step 2:Implement jquery to use AddClass method.

<script>
    $(document).ready(function(){
        $("button").click(function(){
            $("h1, h2, p").addClass("blue");
            $("div").addClass("important");
        });
    });
</script>


Complete Code For AddClass Method In JQuery
<!DOCTYPE html>
<html>
<head>
    <title>How Can I Use AddClass Method In JQuery With Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<style>
    body {
        background: darkolivegreen;
    }

    .important {
        font-weight: bold;
        font-size: xx-large;
    }

    .blue {
        color: blue;
    }
</style>
<body>
<div class="container">
    <br><br><br>
    <div class="text-center">
        <h2 id="color" style="color: White">AddClass Method In JQuery </h2>
    </div>
    <br>
    <br>

    <div class="well">
        <h1>Heading 1</h1>
        <h2>Heading 2</h2>

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

        <div>This is some important text!</div><br>

        <button class="btn btn-primary">Add classes to elements</button>

    </div>

</div>
</body>
</html>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            $("h1, h2, p").addClass("blue");
            $("div").addClass("important");
        });
    });
</script>

Related Post