Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery nth child that is currently visible

I can style every 4th 'item' div like so

  jQuery(".item:nth-child(4n)").addClass("fourth-item");

and that works fine, but then I hide some items, show some others and want to re-do this styling, but only styling every 4th item that is visible. So I have a function that will remove this styling and reapply it, but I need to specify in the reapplying of the style that it is only every 4th visible item, not every 4th item. I know the ":visible" selector but can't seen to chain it with the nth-child selector properly, any ideas?

I've tried various things like this to no avail...

jQuery(".item").removeClass("fourth-item");
jQuery(".item:visible:nth-child(4n)").addClass("fourth-item");
like image 957
Michael Behan Avatar asked Feb 01 '10 09:02

Michael Behan


People also ask

How do you get the nth child selector to skip hidden divs?

In order for the nth-child rules you've declared to work after a user clicks to hide divs, you need to remove the hidden divs from the DOM, so they no longer exist as siblings.

How to get the nth child of an element in jQuery?

jQuery :nth-child() Selector The :nth-child(n) selector selects all elements that are the nth child, regardless of type, of their parent. Tip: Use the :nth-of-type() selector to select all elements that are the nth child, of a particular type, of their parent.

What's the difference between the nth of type () and Nth child () selector?

As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .

How do you use the nth child in querySelector?

To get the nth-child of an element using the querySelector method, pass the :nth-child() pseudo-class as a parameter to the method, e.g. document. querySelector('#parent :nth-child(1)') . The nth-child pseudo-class returns the element that matches the specified position.


1 Answers

:nth-child scans the children of the parent no matter what their styling is. The counting in :nth-child is relative to the parent element, not the previous selector. This is explained in the jQuery docs for :nth-child:

With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class.

Using a more simple method with each does exactly what you want:

$('#test li:visible').each(function (i) {
    if (i % 4 == 0) $(this).addClass('fourth-item');
});
like image 187
Emil Ivanov Avatar answered Oct 17 '22 17:10

Emil Ivanov