Introduction:

In this article we will explain how to use hasClass() in jQuery or why use hasClass() in jQuery or how to check class name exists or not in selected element  with example.

Description:

The jQuery hasClass() method is used to check whether selected elements have exists class name or not. It returns TRUE if the exists class is present in any of the selected elements otherwise it returns FALSE.

Syntax:

$(selector).hasClass(classname) 

 

Example of jQuery hasClass() method  

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Jquery Tutorials</title>
    <script src="Scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                alert($("p").hasClass("myclass"));
            });
        });
    </script>
    
    <p class="myclass">This is a paragraph where exists class.</p>
    <p>This is also a paragraph.</p>
    <button>Click here to check if any p element have an "myclass" class?</button>
</body>
</html>

OutPut:

Use jQuery hasClass()

When you click on button then you will show a message:

 Use jQuery hasClass()

I hope it will help to you.

 

1 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like