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 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.
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>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With