:visible Selector


visible selector

Description: Selects all elements that are visible.

  • version added: 1.0jQuery( ":visible" )

Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.

Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout.

Elements that are not in a document are considered hidden; jQuery does not have a way to know if they will be visible when appended to a document since it depends on the applicable styles.

This selector is the opposite of the :hidden selector. So, every element selected by :visible isn't selected by :hidden and vice versa.

All option elements are considered hidden, regardless of their selected state.

During animations that hide an element, the element is considered visible until the end of the animation. During animations to show an element, the element is considered visible at the start at the animation.

How :visible is calculated was changed in jQuery 1.3.2. The release notes outline the changes in more detail.

Additional Notes:

  • Because :visible is a jQuery extension and not part of the CSS specification, queries using :visible cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :visible to select elements, first select the elements using a pure CSS selector, then use .filter(":visible").
  • Using this selector heavily can have performance implications, as it may force the browser to re-render the page before it can determine visibility. Tracking the visibility of elements via other methods, using a class for example, can provide better performance.

Example:

Make all visible divs turn yellow on click.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>visible demo</title>
<style>
div {
width: 50px;
height: 40px;
margin: 5px;
border: 3px outset green;
float: left;
}
.starthidden {
display: none;
}
</style>
<script src="jquery-1.10.2.js"></script>
</head>
<body>
<button>Show hidden to see they don't change</button>
<div></div>
<div class="starthidden"></div>
<div></div>
<div></div>
<div style="display:none;"></div>
<script>
$( "div:visible" ).click(function() {
$( this ).css( "background", "yellow" );
});
$( "button" ).click(function() {
$( "div:hidden" ).show( "fast" );
});
</script>
</body>
</html>

Demo: