The next, prev, nextAll and prevAll methods are very useful, but not if the elements you are trying to find are not in the same parent element. What I want to do is something like this:
<div>
<span id="click">Hello</span>
</div>
<div>
<p class="find">World></p>
</div>
When the span with the id click
is pressed, I want to match the next element with the class find
, which in this case is not a sibling of the clicked element so next()
or nextAll()
won't work.
The following expression should (barring syntax errors!) find all siblings of the parent that contain a
p.find
element and then find thosep.find
elements and change their colour to blue.Of course, if your page structure is such that
p.find
occurs in a totally different level of hierarchy (sibling of a grandparent for example), it won't work.I think the only way to solve this problem is to do a recursive search over the elements after the current element. There is no simple solution to this problem provided by jQuery. If you only want to find elements in the siblings of your parent element (as is the case in your example), it is not required to do a recursive search, but you have to do multiple searches.
I created an example (actually, it isn't recursive) which does what you want (I hope). It selects all elements after the current clicked element and makes them red:
Try this. It will mark your Element, create a set of Elements matching your selector and collect all Elements from the set following your element.
EDIT
much simpler solution using jquerys index method. the element you call the method from needs to be selectable by the same selector though
to free the function from this handicap, we could youse the browsers own compareDocumentposition
EDIT 2 this is far easier using jQuery's $.grep. here's the new code
when compressing variable names this becomes a mere two liner.
Edit 3 using bitwise operations, this function may be even faster?
My solution would involve adjusting your markup a bit to make the jQuery much easier. If this is not possible or not an appealing answer, please ignore!
I would wrap a 'parent' wrapper around what you want to do...
Now, to find the
find
:This gives you the flexibility to have whatever kind of markup and hierarchy you'd like inside the wrapper I suggested, and still reliably find your target.
Good luck!
I was working on this problem myself today, here's what I came up with:
So in your example
you could now find and manipulate the 'p' element using
I doubt it will perform well on large structures, but here it is :)