jQuery has the handy :even and :odd selectors for selecting the even- or odd-indexed items in a set, which I'm using to clear every other item in a series of floated boxes, as follows:
<div class='2up'>
<div> ... </div>
<div> ... </div>
...
<div> ... </div>
</div>
and
// Clear every 2nd block for 2-up blocks
$('.2up>div:even').css("clear", "both");
This works like a charm.
My question: Is there a straightforward way in jQuery to select every third or fourth item, so I could do the same thing with 3-up or 4-up items?
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.
JavaScript: Get the nth element of a given array Use Array. prototype. slice() to get an array containing the nth element at the first place. If the index is out of bounds, return undefined. Omit the second argument, n, to get the first element of the array.
myclass:eq(1)" ) selects the second element in the document with the class myclass, rather than the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification. Prior to jQuery 1.8, the :eq(index) selector did not accept a negative value for index (though the . eq(index) method did).
Using jQuery :nth-child Selector You have put the position of an element as its argument which is 2 as you want to select the second li element. If you want to get the exact element, you have to specify the index value of the item. A list element starts with an index 0.
Try:
$("div:nth-child(3n+1)").css("clear", "both");
You could use the :nth-child(index/even/odd/equation) selector. http://docs.jquery.com/Selectors/nthChild#index
you can use the :nth-child(index/even/odd/equation) selector.
Example:
<div class='5up'>
<div> ... </div>
<div> ... </div>
...
<div> ... </div>
</div>
and// Clear every 5th block for 5-up blocks
$('.5up>div:nth-child(5n)').css("clear", "both");
or// Clear after every 5th block for 5-up blocks
// note: This will also clear first block.
$('.5up>div:nth-child(5n+1)').css("clear", "both");
No, not as such. The filter
function will let you do that though.
EDIT:
I stand corrected. Use the n-th child function for simplicity.
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