1if ($( "#foo" ).hasClass('className')) {
2 $( "#foo" ).removeClass( 'className');
3} else {
4 $( "#foo" ).addClass( 'className');
5}
1if ($(".mydivclass")[0]){
2 // Do something if class exists
3} else {
4 // Do something if class does not exist
5}
6
1<!doctype html>
2<html lang="en">
3<head>
4 <meta charset="utf-8">
5 <title>hasClass demo</title>
6 <style>
7 p {
8 margin: 8px;
9 font-size: 16px;
10 }
11 .selected {
12 color: red;
13 }
14 </style>
15 <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
16</head>
17<body>
18
19<p>This paragraph is black and is the first paragraph.</p>
20<p class="selected">This paragraph is red and is the second paragraph.</p>
21<div id="result1">First paragraph has selected class: </div>
22<div id="result2">Second paragraph has selected class: </div>
23<div id="result3">At least one paragraph has selected class: </div>
24
25<script>
26$( "#result1" ).append( $( "p" ).first().hasClass( "selected" ).toString() );
27$( "#result2" ).append( $( "p" ).last().hasClass( "selected" ).toString() );
28$( "#result3" ).append( $( "p" ).hasClass( "selected" ).toString() ) ;
29</script>
30
31</body>
32</html>