The hasClass() method in JQuery is used to check if a selected element/elements have the given class name.
<html>
<head>
<title> My First Programme </title>
</head>
<style>
.myClass {
background-color: violet;
}
</style>
<body>
<h1> JQuery </h1>
<p class = "myClass">New Code</p>
<button> Click Here </button>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"> </script>
<script>
$('button').click( function() {
alert($('p').hasClass("myClass"));
});
</script>
</body>
</html>
So, in the above code, we have a <p> element, with the class 'myClass',
<p class = "myClass">New Code</p>
Which is defined in a CSS style property,
<style>
.myClass {
background-color: violet;
}
</style>Now, all we are going to do is, check if the class 'myClass' is a part of <p> element using the 'hasClass()' method.
And we have achieved it using the JQuery statement,
$('button').click( function() {
alert($('p').hasClass("myClass"));
});All we are doing is, check if the class 'myClass' is a part of <p> element using the 'hasClass()' method.
alert($('p').hasClass("myClass"));And if we see the alert raised on click, it displays 'true'. Which means the class 'myClass' is associated to the <p> element.