I have x number of <div>
and I need to select all after n.
<div class=foo>4:00</div>
<div class=foo>5:00</div>
<div class=foo>6:00</div>
<div class=foo>7:00</div>
<div class=foo>8:00</div>
For example, given n=3 and div.foo
, remove all div.foo
after the 3rd div.foo
would yield:
<div class=foo>4:00</div>
<div class=foo>5:00</div>
<div class=foo>6:00</div>
Thanks
jQuery :nth-of-type() SelectorThe :nth-of-type(n) selector selects all elements that are the nth child, of a particular type, of their parent. Tip: Use the :nth-child() selector to select all elements that are the nth child, regardless of type, of their parent.
nextAll() method allows us to search through the successors of these elements in the DOM tree and construct a new jQuery object from the matching elements. The method optionally accepts a selector expression of the same type that we can pass to the $() function.
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.
jQuery :gt() Selector The :gt() selector selects elements with an index number higher than a specified number. The index numbers start at 0.
$('.foo:gt(2)').remove();
Try it out: http://jsfiddle.net/MYY9m/
This uses the greater-than
selector to select all elements who's index is greater than the number provided.
Not as elegant as Patrick DW's solution, but this also works:
$('.foo').eq(2).nextAll().remove();
See http://api.jquery.com/nextAll/
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