Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first visible element with jQuery

Tags:

Trying to get the first visible element of a list using jQuery's :first and :visible pseudo-selectors, as suggested here: https://stackoverflow.com/a/830611/165673 but it's not working:

Fiddle: http://jsfiddle.net/FAY9q/4/

HTML:

<ul>     <li>Item A</li>     <li>Item B</li>     <li>Item C</li> </ul> <ul>     <li style="display:none;">Item A</li>     <li>Item B</li>     <li>Item C</li> </ul> 

JQUERY:

$('li:visible:first').css('background','blue'); 

The first item in each list should turn blue...

like image 566
Yarin Avatar asked Aug 10 '13 14:08

Yarin


People also ask

How do I get only visible elements in jQuery?

Answer: Use the jQuery :visible and :hidden Selector You can simply use the jQuery :visible or :hidden selector to select all the visible or hidden elements in an HTML page. The jQuery :visible selector considered an element visible if they consume space in the document.

Which jQuery filter can be used to check if element is visible?

Answer: Use the jQuery :visible Selector You can use the jQuery :visible selector to check whether an element is visible in the layout or not.

How do you make a Div visible in jQuery?

To toggle a div visibility in jQuery, use the toggle() method. It checks the div element for visibility i.e. the show() method if div is hidden. And hide() id the div element is visible. This eventually creates a toggle effect.

Is element in viewport jQuery?

Check if element is visible in viewport using jquery:If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least partially).


1 Answers

Try using this:

$('ul').find('li:visible:first').css('background','blue'); 

Currently your code is just getting the first visible li element on the page and setting the background colour. This code selects all ul elements then finds the first visible li within each of them and applies the style.

Here it is working: http://jsfiddle.net/FAY9q/5/

like image 124
Joe Avatar answered Oct 05 '22 22:10

Joe