views:

449

answers:

4

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.

A: 

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:

<script type="text/javascript" charset="utf-8">
    $(function () {
        $('#click').click(function() {
            var parent = $(this);
            alert(parent);
            do {
                $(parent).find('.find').css('background-color','red'); 
                parent = $(parent).parent();
            } while(parent !== false);
        });
    });
</script>
Martin Sturm
A: 

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.

dnagirl
A: 

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...

<div class="find-wrapper">
    <div><span id="click">hello</span></div>
    <div><p class="find">world></p></div>
</div>

Now, to find the find:

$(function() {
    $('#click').click(function() {
        var $target = $(this).closest('.find-wrapper').find('.find');
        // do something with $target...
    });
});

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!

Funka