Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: select all elements after nth

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

like image 763
user191688 Avatar asked Jul 30 '10 16:07

user191688


People also ask

How to select nth class in jQuery?

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.

What does nextAll do in jQuery?

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.

How to access nth child 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.

Which of the following is a jQuery selector for selecting items beyond a certain index?

jQuery :gt() Selector The :gt() selector selects elements with an index number higher than a specified number. The index numbers start at 0.


2 Answers

$('.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/
like image 138
user113716 Avatar answered Oct 21 '22 00:10

user113716


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

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

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

like image 3
kingjeffrey Avatar answered Oct 21 '22 01:10

kingjeffrey