Visibility Filter Selectors
In this page:
Visible Elements
':visible' keeps only elements that currently take up layout space -- it excludes anything hidden with display:none or removed from the render tree. An element with zero width and height, or one whose ancestor is hidden, also fails this visibility check.
Example: Visible Elements
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p>Shown</p><p style="display:none;">Hidden</p>
<script>
console.log($("p:visible").length);
</script>
</body>
</html>
Hidden Elements
':hidden' is the inverse of :visible -- it matches elements set to display:none, along with form elements of type="hidden", but not elements merely styled with visibility:hidden or opacity:0.
Example: Hidden Elements
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p>Shown</p><p style="display:none;">Hidden</p>
<script>
console.log($("p:hidden").length);
</script>
</body>
</html>
Show Hidden Items
Selecting with ':hidden' and calling .show() on the result is a common pattern for revealing content that started out hidden, such as an accordion panel or a collapsed menu. Toggling between visible and hidden states like this is the basis of most simple show/hide UI interactions.
Example: Show Hidden Items
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p style="display:none;">Panel</p>
<button id="btn">Show</button>
<script>
$("#btn").on("click", function() {
$("p:hidden").show();
});
</script>
</body>
</html>
Hide Visible Items
Selecting with ':visible' and calling .hide() lets you conceal only the currently-shown elements in a group, leaving already-hidden ones untouched. This pairing gives you precise control to hide exactly the elements a user can currently see, and nothing else.
Example: Hide Visible Items
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p>A</p><p style="display:none;">B</p>
<button id="btn">Hide</button>
<script>
$("#btn").on("click", function() {
$("p:visible").hide();
});
</script>
</body>
</html>
Visibility with Classes
Visibility filters combine with class or attribute selectors, like '.item:visible', to narrow a broader group down to just the subset that's currently on screen. Chaining filters like this lets you scope a broad group down to exactly the elements relevant to the current UI state.
Example: Visibility with Classes
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p class="item">Shown</p><p class="item" style="display:none;">Hidden</p>
<script>
console.log($(".item:visible").length);
</script>
</body>
</html>
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: