CodesJava

Easy learning with example program codes

jQuery hasClass()

The jQuery hasClass() method checks whether the selected elements have specified class name or not.

Return Value:

TRUE:  If the specified class is present in any of the selected elements.

FALSE. If the specified class is not present in any of the selected elements.

Syntax:

$(selector).hasClass(classname)  

Classname:

  • Classname is a compulsory parameter of jQuery hasClass() method, as it specifies the name of the CSS class to search for.

 

Example 1

<!DOCTYPE html>  
<html>  
<head>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>    
<script>  
$(document).ready(function(){  
	$("button").click(function(){  
    	alert($("p").hasClass("yo"));  
	});  
});  
</script>  
<style>  
.yo {  
	font-size: 200%;  
	color: red;  
}  
</style>  
</head>  
<body>  
<h1>Hello!</h1>  
<p class="yo">How are you?</p>  
<p>Nice to see you again.</p>  
<button>Click me</button>  
</body>  
</html>

Try it

JS Bin on jsbin.com

Example 1

<!DOCTYPE html>  
<html>  
<head>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>    
<script>  
  $(document).ready(function() {	 
   $(".btn").click(function(){   
	var className = $(this).attr("id");  
	$("ul li").each(function() {  	 
 	if ($(this).hasClass(className)) {  
  	$(this).fadeTo('3000', 0.0).fadeTo('5000', 1.0);   	 
 	}  
	}); 	 
   });   
  });  
  </script>	 
  <style>  
  ul{  
   font-family: monospace;  
   font-size: 15px;  
   font-family: monospace;   
   font-style: normal;  
   font-size-adjust: none;  
   width:200px;	 
   padding:0px;   
  }  
 
  ul li{  
   background-color:turquoise;  
   width:100px;  
   margin:5px;  
   padding:5px;  
   list-style-type:none;  
   width:200px;  
  }  
  </style>  
 </head>  
 <body>  
 <h1>Click the buttons and I will show the matched classes</h1>	 
 <ul>  
  <li class="red">Red</li>    
  <li class="green">Green</li>  	 
  <li class="green red">Green Red</li>  
  <li class="blue">Blue</li>  
 </ul>   
 <input type="button" class="btn" value="Red Class" id="red">  
 <input type="button" class="btn" value="Green Class" id="green">  
 <input type="button" class="btn" value="Blue Class" id="blue">  
 
 </body>  
</html>

Try it

JS Bin on jsbin.com

Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status