Skip to content

Instantly share code, notes, and snippets.

@ezarko
Created June 1, 2016 14:10
Show Gist options
  • Save ezarko/c9573502f0bf825b87e13b79763df6d2 to your computer and use it in GitHub Desktop.
Save ezarko/c9573502f0bf825b87e13b79763df6d2 to your computer and use it in GitHub Desktop.
Given two DOM elements in the same document, find the closest common ancestor (which could be one of the elements).
function findCommonParent(a, b) {
var $a = $(a),
$b = $(b),
found;
/*
* A complicated one-liner here; with each element a & b,
* get the set of parents,
* and add to this the element
* .add() will sort the elements in document order though
* e.g. html, body, etc.
* which is the opposite of .parents()
* so use .get() to convert to an array,
* so we can .reverse()
* and wrap it in a $() to convert back to a jquery set
* to allow us to use .each()
*/
$a = $($a.parents().add($a).get().reverse());
$b = $($b.parents().add($b).get().reverse());
$a.each(function(i1, p1) {
$b.each(function(i2, p2) {
if (p1 == p2) {
found = p2;
return false; // break $b.each()
}
});
return ! found; // break $a.each() if found
});
return found;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment