Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the first shared parent of two elements

Lets say I have this DOM structure

<body>
    <p>
        Hello
        <i>how <b>are</b> you</i>
        and
        <i>what <b>are <tt>you</tt> going</b> to</i>
        eat tonight?
    </p>
</body>

Using jQuery I want to get to know the FIRST shared parent of the

<b>are</b>

and the

<tt>you</tt>

From down to top this would be the < p > not the < body > tag.

Any ideas on how to determine the first shared parent utilizing jQuery?

like image 730
paul Avatar asked Nov 04 '10 17:11

paul


2 Answers

Like this:

$(a).parents().filter(function() { return jQuery.contains(this, b); }).first();

If b is a selector (as opposed to a DOM element), you can change it to:

$(a).closest(':has(b)');

This is shorter, but substantially slower.

The order of a and b is irrelevant; if b is closer to the parent, it will be faster.

like image 77
SLaks Avatar answered Sep 28 '22 13:09

SLaks


You can combine .parents() with .filter(), like this:

$("b:first").parents().filter($("tt").parents()).first()
//or more generic:
$(elem1).parents().filter($(elem2).parents()).first()

This gets all shared parents, you can then take the .first() or .last()...whatever's needed.

You can test it here. Note this is much faster than .has() since we're just comparing 2 DOM element sets, not recursively comparing many. Also, the resulting set will be in the order going up the document, in this example <p> then <body>.

like image 23
Nick Craver Avatar answered Sep 28 '22 12:09

Nick Craver