jQuery: Given a selector, find only its visible elements
Asked Answered
C

2

34

This should be an easy one. I have a variable that I've already declared called $listItems. The declaration looks like this:

var $listItems = $ul.children('li'); // $ul is just a selected unordered list

Later in my code, I'd like to only get the ones that are currently visible. How would I go about that? Something like:

$listItems.parent().children(':visible')?

Thanks.

Cahoot answered 29/10, 2010 at 0:6 Comment(0)
G
73

You can use .filter() to narrow down a set of elements to only those that match a selector (or a function), like this:

$listItems.filter(':visible')
Gildus answered 29/10, 2010 at 0:8 Comment(3)
Yeah that's what I meant Nick ;)Timothy
this is especially helpful if you need to filter on multiple values. E.g. selected and visible. +1 for a good solution!Insnare
FWIW, jQuery defines an element as visible "if they consume space in the document". An element could have its visibility set to hidden, so it's not actually seen on the page, but :visible would still return the element.Logroll
H
4

You have it with the :visible selector. It can be used in any of the jQuery collection methods $(), filter(), children(), find(), etc.

Note: There is a difference between something that is visible on the page and has its visibility property set.

Hence answered 29/10, 2010 at 0:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.