Alex Rivera | Logout

jQuery find next/prev elements of a certain class but not necessarily siblings

Asked 2009-12-01T16:52:55.340
20

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.

Edit
Report

1 Answer

0

The following expression should (barring syntax errors!) find all siblings of the parent that contain a p.find element and then find those p.find elements and change their colour to blue.

$(this).parent().nextAll(":has(p.find)").find(".find").css('background-color','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.

answered 2009-12-01T18:11:12.700

Your Answer