Conditional Checks with is() and has()
In this page:
is()
.is() tests the current selection against a selector and returns a plain true or false, without changing what's selected. It's the standard way to ask 'does this element match X?' without needing to compare tag names or classes manually.
Example: is()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="text" class="active">Text</p>
<script>
console.log($("#text").is(".active"));
</script>
</body>
</html>
is() with Functions
is() can also take a function instead of a selector, letting you write custom logic to decide whether an element counts as a match. This is useful for conditions that aren't expressible as a plain CSS selector, like checking a data attribute's numeric value.
Example: is() with Functions
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="field" value="hello">
<script>
console.log($("#field").is(function() { return $(this).val().length > 3; }));
</script>
</body>
</html>
has()
has() keeps only the elements in a selection that contain a matching descendant element, rather than testing the elements themselves. This is different from filter() or is(), which test the selected elements directly instead of what's nested inside them.
Example: has()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div class="box"><span>Inner</span></div><div class="box"></div>
<script>
console.log($(".box").has("span").length);
</script>
</body>
</html>
Combining Checks
is() and has() are useful for conditional UI logic, such as only enabling a button when a form has() at least one checked checkbox, or checking is() an element already has an active class before toggling it. Combining them lets you branch on both an element's own state and its contents.
Example: Combining Checks
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<form id="myForm"><input type="checkbox" checked></form>
<button id="submitBtn">Submit</button>
<script>
const enabled = $("#myForm").has(":checked").length > 0;
console.log(enabled);
</script>
</body>
</html>
Practical Checks
Conditional checks like these help you make decisions before changing the page, such as confirming an element is() currently visible before trying to animate it. This avoids running code against elements that aren't in the state your logic assumes.
Example: Practical Checks
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="display:block">Box</div>
<script>
if ($("#box").is(":visible")) {
$("#box").fadeOut();
}
</script>
</body>
</html>
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: