jQuery DETECT the PARENT to the unknown level above?

advertisements

How to detect the parent at unknown level above?

For example:

<div id="parent-a">
    <....>
        <....>
            <div class="the-child" /> <!-- Comment 1 -->
        </....>
    </....>
</div>
<div id="parent-b">
    <....>
        <div class="the-child" /> <!-- Comment 2 -->
    </....>
</div>

<....> DOMS may be any unknown elements (in any much numbers) in between.

Then if i look upward from the-child at Comment 1, how do i know its parent is div#parent-a ?

Same thing again, if i look upward from the-child at Comment 2, how do i know its parent is div#parent-b ?


You can use jQuery's parents() for such tasks. But you have to have at least some identifiers for the parent element you want to target, so, e.g., this would work:

// for version one
var parent = $( '.the_child' ).parents( '#parent-a' );

// for version two
var parent = $( '.the_child' ).parents( '#parent-b' );

In both cases the first element, which is an ancestor of the_child element and matches the given selector is returned (if it exists).