To check if element has particular class or not in jQuery we need to write the code like as shown below
if($(this).hasClass("purplcls"))
$(this).removeClass("purplcls");
else
$(this).addClass("purplcls");
|
If you want complete example to check if div has particular class or not we need to write the code like as shown below
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Check If Div Element has Particular Class or Not</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function(){
$('#divdetails').addClass("purplcls");
$('#divdetails').click(function () {
if($(this).hasClass("purplcls")){
$(this).removeClass("purplcls");
$(this).addClass("blucls");
}
else{
$(this).removeClass("blucls");
$(this).addClass("purplcls");
}
})
})
</script>
<style type="text/css">
.purplcls {
background:purple;
color:White;
}
.blucls {
background: blue;
}
</style>
</head>
<body>
<form id="form1">
<div id="divdetails" style=" cursor:pointer; width:20%; height:50px; text-align:center; font-weight:bold">
Sample Div
</div>
</form>
</body>
</html>
|
Live Demo
To check live demo click on below purple color div here we will check if div has purple color class or not in case if it there we will change to blue color class otherwise purple color class using jQuery.
Sample Div
|
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.