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).
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.
To add the previous element to current jQuery selection, use the insertBefore() method.
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.
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.
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.
jQuery has built in support as required by you,
$($('input')[0]).next('input')
next
$($('input')[0]).prev('input')
previous
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