Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select next 2 (or more than 2) items using jQuery .next()?

using jQuery's .next function I want to show next 2 items. By default it selects only just next item.

I need control, like sometimes I need next 2, sometime next 3

like image 397
Jitendra Vyas Avatar asked Oct 11 '10 09:10

Jitendra Vyas


People also ask

Can you select multiple elements in jQuery?

In jQuery, you can select multiple elements by separate it with a comma “,” symbol.

What does .next do in jQuery?

next() method allows us to search through the immediately following sibling 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 can I get next sibling in jQuery?

jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.

Which of the following jQuery method is used to find all next sibling elements after the current element?

jQuery nextAll() Method The nextAll() method returns all next sibling elements of the selected element.


1 Answers

You can use .nextAll() and a :lt() selector, for example:

.nextAll(':lt(2)') //next 2
.nextAll(':lt(3)') //next 3

Try it out here. If you need it to be programmatic (instead of string concatenation) and change it easily, use .slice() instead:

.nextAll().slice(0, 2) //next 2
.nextAll().slice(0, 3) //next 3

This method allows you to pass as a parameter the number you need a bit easier. You can test it here.

like image 87
Nick Craver Avatar answered Sep 19 '22 09:09

Nick Craver