There are 2 methods that can be used in jQuery to determine whether an element contains a certain class. Both methods have the same functionality. The two methods are as follows: (personally like to use hasClass())
1. hasClass(‘classname’)
2. is(‘.classname’)
The following is an example of whether a div element contains a redColor:
1. Use is('.classname') method
$('div').is('.redColor')
2. The method of using hasClass('classname') (note that the lower version of jquery may be hasClass('.classname'))
$('div').hasClass('redColor')
The following is an example of detecting whether an element contains a redColor class, and if so, change its class to blueColor.
<html>
<head>
<styletype="text/css">
.redColor {
background:red;
}
.blueColor {
background:blue;
}
</style>
<scripttype="text/javascript"src="jquery-1.3.2.min.js"></script>
</head>
<body>
<h1>jQuery check if an element has a certain class</h1>
<divclass="redColor">This is a div tag with class name of "redColor"</div>
<p>
<buttonid="isTest">is('.redColor')</button>
<buttonid="hasClassTest">hasClass('.redColor')</button>
<buttonid="reset">reset</button>
</p>
<scripttype="text/javascript">
$("#isTest").click(function () {
if($('div').is('.redColor')){
$('div').addClass('blueColor');
}
});
$("#hasClassTest").click(function () {
if($('div').hasClass('redColor')){
$('div').addClass('blueColor');
}
});
$("#reset").click(function () {
location.reload();
});
</script>
</body>
</html>
初始效果:
点击is('.redColor')后的效果:
The effect of clicking hasClass('redColor') is the same as the effect of clicking is('.redColor'), and the effect of clicking reset is the same as the initial effect.