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
In jQuery, you can select multiple elements by separate it with a comma “,” symbol.
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.
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.
jQuery nextAll() Method The nextAll() method returns all next sibling elements of the selected element.
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.
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