How to choose every last child that received a specific css property?

I am trying to select every last element that received display:block properties in a hidden parent element.

Here is an example script for the game.

HTML:

 <ul style="display:none;"> <li>1</li> <li>2</li> <li>3</li><!-- my goal is find last visible child on every hidden ul --> <li style="display:none;">4</li> </ul> 

JQuery

 $('ul').each(function() { visibleCountOnEachUl =+ 0; $(this).children('li').each(function(index) { if ( $(this).css('display') === 'block' ) { visibleCountOnEachUl += 1; $(this).addClass('theseAreVisible'); //this part works; //i can select elems elems which got display:block //but can't select the last elem on each ul //if ( index === (visibleCount-1) ) { //$(this).addClass('last-visible'); //} } }); }); $('ul').find('li:visible:last').addClass('last-visible'); //This won't effect on child elements while their parent is hidden. 

I found this similar question , but the solution works with the visible parent.

+4
source share
2 answers

Try the following:

 $('ul').each(function() { $(this).children('li').each(function(index, elem) { var l = $(elem).parent().find('li').filter(function() { return $(this).css('display') === 'block'; }).length; if (index == l-1) $(this).addClass('last-visible'); }); }); 

This is where jsFiddle works.

+3
source

This will work when the parent element is displayed: block:

 $('ul li:visible:last').addClass('select'); 

When the parent element is displayed: none, you must make the element absolute, visible: hidden or place them from the viewport.

 if( $('ul').css('display','none') ){ $('ul').css({ 'display':'block', 'position': 'absolute', 'visibility': 'hidden'}); $('ul li:visible:last').addClass('select'); } 
-1
source

All Articles