jquery selecting nth-child skipping hidden elements
css-selectors, jquery
Solution
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');
}
});
Problem
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> ```