SoFunction
Updated on 2025-02-28

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

In jquery, two methods can be used to determine whether an element contains a certain class. Both methods have the same function.

The 2 methods are as follows:

 1. is(‘.classname')

2. hasClass(‘classname')

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

1. Use is('.classname') method

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

2. Use hasClass('classname') method (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. When it contains, its class will be changed to a 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."></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 >is('.redColor')</button>
<button >hasClass('.redColor')</button>
<button >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 () {
();
});
</script>
</body>
</html>

The above article using jquery to determine whether an element contains a specified class (class) example is all the content I have shared with you. I hope it can give you a reference and I hope you can support me more.