Skip to content

Instantly share code, notes, and snippets.

@perry-mitchell
Created January 10, 2017 13:40
Show Gist options
  • Save perry-mitchell/3466505ef841be6b8030fbc6fddea7c4 to your computer and use it in GitHub Desktop.
Save perry-mitchell/3466505ef841be6b8030fbc6fddea7c4 to your computer and use it in GitHub Desktop.
Find common parent element of n nodes
/**
* Find common parent node
*/
export function findCommonParent(...nodes) {
let nodeParents = nodes.map(node => findParents(node)),
firstNodeParents = nodeParents[0],
topParent = firstNodeParents[0];
if (nodeParents.some(parents => parents.indexOf(topParent) !== 0)) {
// no common parent
return null;
}
for (let i = firstNodeParents.length - 1; i >= 0; i -= 1) {
if (nodeParents.every(parents => parents.indexOf(firstNodeParents[i]) >= 0)) {
return firstNodeParents[i];
}
}
return null;
}
/**
* Find all node parents
* Taken from: http://stackoverflow.com/a/5350888
*/
export function findParents(node) {
var nodes = [node];
for (; node; node = node.parentNode) {
nodes.unshift(node);
}
return nodes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment