Reputation: 2659
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
Upvotes: 18
Views: 6195
Reputation: 79
It is efficient to use slice or eq since gt does not accept variables. for example
//will not work
var items_to_remove = 8;
$("li:gt(items_to_remove)").remove();
//will work
var items_to_remove = 8;
$('li').slice(items_to_remove).remove();
Upvotes: 0
Reputation: 15270
Not as elegant as Patrick DW's solution, but this also works:
$('.foo').eq(2).nextAll().remove();
See http://api.jquery.com/nextAll/
Upvotes: 2
Reputation: 15270
You can also do:
$('.foo').slice(3).remove();
See http://api.jquery.com/slice/
Upvotes: 3
Reputation: 322492
$('.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.
Upvotes: 21