Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




CSS METHODS - hasClass()


The hasClass() method in JQuery is used to check if a selected element/elements have the given class name.


Example :



<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://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
	  
      	<script>
      
      		$('button').click( function() {
				alert($('p').hasClass("myClass"));
			});
			
      	</script>      
   </body>
</html>


Output :




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.