Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to get the next or previous element from a selection

Tags:

jquery

How can I get the previous or next element from a jQuery selection?

Basically, I will have a set of elements, say all inputs:

$('input')

When I have a single input, I also need to get the previous and next input. Something like:

$(this).prev('input')
$(this).next('input')

However, the inputs are not siblings and I don't want just the next DOM element. I want the next element in the jQuery selection (inputs in this case).


I know I can iterate through a jQuery selection with

.each(function(...

But I don't need to go over all of the elements, just the one before and after.

The elements will also be dynamically ordered (using jQuery UI sortables).

like image 551
codegoalie Avatar asked Jun 11 '09 15:06

codegoalie


People also ask

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.

What is used to add the previous selection to the current selection in jQuery?

To add the previous element to current jQuery selection, use the insertBefore() method.

What does find () return in jQuery?

jQuery find() Method The find() method returns descendant elements of the selected element. A descendant is a child, grandchild, great-grandchild, and so on. The DOM tree: This method traverse downwards along descendants of DOM elements, all the way down to the last descendant.

What is '$' in jQuery?

The jQuery object :) From the jQuery documentation: By default, jQuery uses "$" as a shortcut for "jQuery" So, using $("#id" ) or jQuery("#id") is the same. Follow this answer to receive notifications.


2 Answers

You could do something like this:

var inp = $('input');

var index = inp.index(this);
var next = inp[index+1];
var prev = inp[index-1];

Note that prev and next, just like this are not jQuery objects but DOM object now. To make them jQuery objects you need to wrap them in the $() function.

like image 112
Pim Jager Avatar answered Sep 25 '22 20:09

Pim Jager


jQuery has built in support as required by you,

$($('input')[0]).next('input')

next

 $($('input')[0]).prev('input')

previous

like image 40
Subba Rao Avatar answered Sep 24 '22 20:09

Subba Rao