Use jquery to determine whether an element contains a specified instance of class of class

  • 2021-07-21 05:55:36
  • OfStack

In jquery, you can use two methods to determine whether an element contains a certain class (class). Both methods have the same function.

The two methods are as follows:

1. is ('. classname')

2. hasClass ('classname')

Here is an example of whether an div element contains an redColor:

1. Method using is ('. classname')

$('div').is('.redColor')

2. The method of using hasClass ('classname') (note that a lower version of jquery may be hasClass ('. classname'))

('div'). hasClass ('redColor') The following is an example of detecting whether an element contains an redColor class, and if so, changing its class to blueColor.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.redColor { 
background:red;
}
.blueColor { 
background:blue;
}
</style>
<script type="text/javascript"src="jquery-1.8.1.min.js"></script>
</head>
<body>
<h1>jQuery check if an element has a certain class</h1>
<div class="redColor">This is a div tag with class name of "redColor"</div>
<p>
<button id="isTest">is('.redColor')</button>
<button id="hasClassTest">hasClass('.redColor')</button>
<button id="reset">reset</button>
</p>
<script type="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>

Related articles: