In jQuery, I want to add a class to all visible elements that are the 5th child or greater, and another class to each element that isn't a 4th child. Previously, I was doing this:
$overlay.find('> .container .content .selector').not(':nth-child(4n)').addClass('hasRightMargin');
$overlay.find('> .container .content .selector:nth-child(n+5)').addClass('hasTopMargin');
However, now I'm toggling the visibility of the first .selector
, and 开发者_开发知识库:nth-child
does not take visibility into account, so this does not work as I want, because it's still counting the invisible element:
$overlay.find('> .container .content .selector:visible').not(':nth-child(4n)').addClass('hasRightMargin');
$overlay.find('> .container .content .selector:visible:nth-child(n+5)').addClass('hasTopMargin');
Is there a way to do what I want in one selector? Or will I have to loop through all .selector
elements using each
and filter them there manually?
I think this should do the trick.
$overlay.find('> .container .content .selector:visible:not(:odd:odd)').addClass('hasRightMargin');
$overlay.find('> .container .content .selector:visible:gt(3)').addClass('hasTopMargin');
Your primary issue is that nth child selects all elements that are the nth child of their parent, not the nth elements in the set. Also, keep in mind that selectors such as :odd,:even,:gt,:lt are 0-indexed. So :odd selects the elements 1,3,5,etc. which are the 2nd,4th,6th elements on the page. And :odd:odd selects every 4th element on the page. Likewise, :gt(3) selects all elements with index of 4 or more, which is the 5th element and beyond.
See here for a jsfiddle that, I think, demonstrates what you were looking for. Note the hidden divs that get passed over.
Can you .find() on visible elements before you apply your :nth-child selector? Maybe something like
$overlay.find("> :visible").find('.container .content .selector').not(':nth-child(4n)')...
精彩评论