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.

Keavon
  • 6,837
  • 9
  • 51
  • 79
Matt
  • 23,363
  • 39
  • 111
  • 152

2 Answers2

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')
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • Yeah that's what I meant Nick ;) – fehays Oct 29 '10 at 00:16
  • this is especially helpful if you need to filter on multiple values. E.g. selected and visible. +1 for a good solution! – Lucas B Jul 30 '12 at 19:10
  • 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. – jacroe Mar 28 '17 at 17:53
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.

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174