Reputation: 116383
I'm given a jQuery object $myObject
and a DOM element myElement
contained in $myObject
.
How can I find the next DOM element contained in $myObject
right after myElement
?
Upvotes: 2
Views: 3100
Reputation: 91617
Pure JavaScript:
var nextElement = myElement.nextSibling;
Edit: Reading some of your comments, it looks like I may have misunderstood what you are looking for. You mention that your elements are added to $myObject
using .add()
. It sounds like you are trying to access the elements in the order they were added to $myObject
. Is that right? Elements are stored in a jQuery object in the order they appear in the DOM. The order they are added to the jQuery object is not preserved. You can get the next element in the set of matched elements using .index()
to find the position of myElement
and then get the next one:
var idx = $myObject.index(myElement);
var nextElement = $myObject[idx + 1];
But the next element will be according to DOM order, not the order the elements were added. To get that, you'd need to store the order yourself.
See this demo: http://jsfiddle.net/gilly3/Z96Gd/
Upvotes: 6
Reputation: 349182
Wrap the DOM element myElement
in a $
, so that JQuery methods can be used. Then, use $(myElement).next().get(0)
. next()
moves to the next element, while get(0)
returns the first DOM element of the selector.
Instead of using JQuery methods, you can also switch to native DOM properties, such as myElement.nextSibling
.
Upvotes: 3