YouTip LogoYouTip

Sel Visible

## jQuery :visible Selector The `:visible` selector in jQuery is a powerful filtering selector used to target all elements that are currently visible on the page. --- ## Definition and Usage The `:visible` selector selects every element that is currently visible in the DOM. In jQuery, an element is considered **visible** if it consumes space in the document layout. Conversely, an element is considered **hidden** (and thus *not* selected by `:visible`) if it meets any of the following criteria: * It has a CSS property of `display: none`. * It is a form element with `type="hidden"` (e.g., ``). * Its `width` and `height` are explicitly set to `0`. * It has an ancestor (parent, grandparent, etc.) that is hidden, which in turn hides the child element from the page layout. > **Note on `visibility: hidden` and `opacity: 0`:** > Elements with `visibility: hidden` or `opacity: 0` are still considered **visible** by jQuery because they still occupy physical space in the document layout. To select these, you must use alternative CSS property filters. --- ## Syntax ```javascript $(":visible") ``` ### Usage Variations * **Select all visible elements on the page:** ```javascript $(":visible") ``` * **Select only visible elements of a specific tag type (e.g., `

`):** ```javascript $("p:visible") ``` * **Select visible child elements within a specific container:** ```javascript $("#container-id .item:visible") ``` --- ## Code Examples ### Example 1: Basic Usage The following example demonstrates how to select and style all visible `

` elements when a button is clicked. ```html

jQuery :visible Selector Demo

This is a visible paragraph.

This is a hidden paragraph (display:none) and won't be affected.

This is another visible paragraph.

``` ### Example 2: Toggling and Counting Visible Elements You can combine `:visible` with other jQuery methods to perform dynamic checks, such as counting how many elements are currently displayed on the screen. ```javascript // Count the number of visible list items var visibleItemsCount = $("li:visible").length; console.log("There are " + visibleItemsCount + " visible items."); ``` --- ## Performance Considerations Because `:visible` is a jQuery extension and not part of the official CSS specification, queries using `:visible` cannot take advantage of the high-speed native DOM `querySelectorAll()` method. To achieve optimal performance when using this selector: 1. **Narrow down the search space first:** Avoid using `$(":visible")` globally. Instead, prefix it with a tag name, ID, or class name (e.g., `$("#menu-items .item:visible")`). 2. **Filter an existing jQuery collection:** ```javascript // Recommended for better performance on large DOM trees: $("p").filter(":visible").css("color", "red"); ```
← Jq Sel RootSel Hidden β†’