jQuery hasClass() function is used to determine whether any of the matched elements are assigned the given class.
Try it Yourself - Copy paste code in Online HTML Editor to see the result
Try it Yourself - Copy paste code in Online HTML Editor to see the result
Description
Determine whether any of the matched elements are assigned the given class.
Syntax
$(selector).hasClass( className )
className - The class name to search for.
Examples
Example 1
Looks for the paragraph that contains 'selected' as a class.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hasClass demo</title>
<style>
p {
margin: 8px;
font-size: 16px;
}
.selected {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<p>This paragraph is black and is the first paragraph.</p>
<p class="selected">This paragraph is red and is the second paragraph.</p>
<div id="result1">First paragraph has selected class: </div>
<div id="result2">Second paragraph has selected class: </div>
<div id="result3">At least one paragraph has selected class: </div>
<script>
$("#result1").append($("p").first().hasClass("selected").toString());
$("#result2").append($("p").last().hasClass("selected").toString());
$("#result3").append($("p").hasClass("selected").toString());
</script>
</body>
</html>
Example 2
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
alert($("p").hasClass("intro"));
});
});
</script>
<style>
.intro {
font-size: 120%;
color: red;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p class="intro">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Does any p element have an "intro" class?</button>
</body>
</html>
Comments
Post a Comment