How To Use HasClass Method In JQuery With Examples

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

In JQuery The hasClass() checks whether the elements with the specified class name exists or not.So today in this article we see how to use it

How To Use HasClass Method In JQuery With Examples

Syntax

$(selector).hasClass(classname)
 

Parameter: It accepts a “className” parameter which specifies the class name need to search in the selected element.

Return Value: It returns true if the search is successful otherwise false.

Example(1)

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

 

<h1>Heading 1</h1>

<p class="find">Bajarangisoft</p>
<p>This is normal paragraph.</p>

<button class="btn btn-success">Click me!</button>



Step 2:Implement jQuery to use hasClass() method.
 

<script>
    $(document).ready(function() {
        $("button").click(function() {
            alert($("p").hasClass("find"));
        });
    });
</script>



Complete Code For Using hasClass Method In JQuery
 

<!DOCTYPE html>
<html>
<head>
    <title>How To Use HasClass 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: black;
    }

    .find {
        font-size: 120%;
        color: green;
    }

</style>
<body>
<div class="container">
    <br><br><br>
    <div class="text-center">
        <h1 id="color" style="color: White;">Use HasClass Method In JQuery </h1>
    </div>
    <br>
    <div class="col-md-2"></div>
    <div class="col-md-8">
        <div class="well">
            <h1>Heading 1</h1>

            <p class="find">Bajarangisoft</p>
            <p>This is normal paragraph.</p>

            <button class="btn btn-success">Click me!</button>

            <script>
                $(document).ready(function () {
                    $("button").click(function () {
                        alert($("p").hasClass("find"));
                    });
                });
            </script>
        </div>
    </div>
    <div class="col-md-2"></div>
</div>
</body>
</html>

Related Post