JSFiddle - React, Tailwind, and code Playground
by AndyE
HTML
<div>
<div id="thisOne">
<div>
<div>
<div>
<div id="a">
first element
</div>
</div>
<div id="b">
second element
</div>
</div>
</div>
<div>
<div id="c">
third element
</div>
<div id="d">
fourth element
</div>
</div>
</div>
</div>
JavaScript
function getCommonAncestor(node1 /*, node2, node3, ... nodeN */) {
if (arguments.length < 2)
throw new Error("getCommonAncestor: not enough parameters");
var i,
method = "contains" in node1 ? "contains" : "compareDocumentPosition",
test = method === "contains" ? 1 : 0x0010,
nodes = [].slice.call(arguments, 1);
rocking:
while (node1 = node1.parentNode) {
i = nodes.length;
while (i--) {
if ((node1[method](nodes[i]) & test) !== test)
continue rocking;
}
return node1;
}
return null;
}
var n1 = document.getElementById("a"),
n2 = document.getElementById("b"),
n3 = document.getElementById("c"),
n4 = document.getElementById("d");
alert(getCommonAncestor(n1, n2, n3, n4).id);