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>
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');
}
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With