jquery: select all elements after nth

2019-04-04 00:26发布

问题:

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

回答1:

$('.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.

  • http://api.jquery.com/gt-selector/


回答2:

You can also do:

$('.foo').slice(3).remove();

See http://api.jquery.com/slice/



回答3:

Not as elegant as Patrick DW's solution, but this also works:

$('.foo').eq(2).nextAll().remove();

See http://api.jquery.com/nextAll/



回答4:

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();