Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery selecting nth-child skipping hidden elements [duplicate]

I have the following html structure:

<ul class="products">
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
</ul>

I having the following jquery:

$(".products li:nth-child(4)").addClass("last");

As you can see the above will add a class of last to every 4th <li>.

However in my HTML there might be a hidden <li> using display:none; via jquery.

Is there a way to skip past the hidden elements? So in theory i should have the following:

<ul class="products">
<li><a href="#"></a></li>
<li style="display:none;"><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li class="last"><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li class="last"><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
</ul>
like image 384
danyo Avatar asked Jan 29 '26 12:01

danyo


2 Answers

You can simply limit your selection to exclude hidden items:

$('.products li').filter(':visible');

Unfortunately you can't use nth selectors here, since you don't want to count the hidden elements., so you could just iterate over the items and change every fourth one.

$('.products li').filter(':visible').each(function(i) {
    var modulus = (i + 1) % 4;
    if (modulus === 0) { 
        $(this).addClass('last');
    }
});
like image 113
Mike Brant Avatar answered Jan 31 '26 22:01

Mike Brant


Maybe you could try using the index instead of using a selector of nth child, along with lorenzos solution?

$('li:visible').each(function(i){
    if((i+1) % 4 == 0){
        $(this).addClass('temp');
    }
});

UPDATED fiddle here

like image 37
ntgCleaner Avatar answered Jan 31 '26 22:01

ntgCleaner