Search code examples
jquerytreesiblingsparents

Jquery First occurrence tree traversal up parents/siblings


What is the best way to get closest (up tree) given a class, but it can be a sibling of a parent.

I want to get "errors1" element start with element ".start"

<div>
    ...
    <div class="errors">errors2</div>
    <div>
        .....
        <div class="errors">errors1</div>
        ...
        <div>...</div>
        <div>
            .....
            <div class="start"></div>            
        </div>     
    </div>
</div>

Made a script but its really bad and doesnt work at all.

http://jsfiddle.net/9DfCJ/1/

Thanks

EDITED: Added "..." to enhance that structure is dynamic. The point is to find the closest ".errors" up tree.


Solution

  • Great question. The code below should work for you. It loops over each parent of .start until it finds an element with .errors. Then it alerts the text of the .errors element that is closest to .start.

    jQuery(function($){
    
        var $start = $('.start'),
            $parents = $start.parents();
    
        $parents.each(function(){
            var $this = $(this),
                $thisErrors = $this.find('.errors'),
                numErrors = $thisErrors.length;
    
            if(numErrors){
                alert($thisErrors.eq(numErrors-1).text());
                return false;
            }
    
        });
    
    });