• jQuery Video Tutorials

jQuery :visible Selector



The :visible selector in jQuery is used to select elements that are currently visible in the DOM.

Following are the scenarios where elements are not considered as visible:

  • Elements with a CSS property of display: none.
  • Elements with a CSS property of visibility: hidden.
  • Elements with an opacity of 0.

Note: The :visible selector does not work with elements that have height or width set to 0.

Syntax

Following is the syntax of :visible selector in jQuery −

$(":visible")

Parameters

The :visible selects all elements that are currently visible in the DOM.

Example 1

In the following example, we are using the :visible selector to select all visible <p> elements −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p:visible").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <p>This paragraph is visible.</p>
    <p style="display: none">This paragraph is hidden.</p>
    <p style="visibility: hidden;">This paragraph is not visible.</p>
</body>
</html>

After executing the above program, the :visible selects all visible <p> elements and highlights them with yellow background color.

Example 2

In this example, we are displaying an alert (that shows the count) of visible div elements −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            var visibleDivs = $("div:visible").length;
            alert("There are " + visibleDivs + " visible div elements.");
        });
    </script>
</head>
<body>
    <div>This div is visible.</div>
    <div style="display : none">This div is hidden.</div>
</body>
</html>

When we execute the above program, It shows an alert with the count of visible div elements.

jquery_ref_selectors.htm
Advertisements