JSFiddle - React, Tailwind, and code Playground

HTML

<div>
    <div id="correct">
        <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(node /*, node2, node3, ... nodeN */) {
  if (!node)
    throw new Error('getCommonAncestor: need at least one Node');

  var nodes   = [].slice.call(arguments, 1)
    , method  = 'compareDocumentPosition'
    , bitmask = 0x0010;
  if ('contains' in node) {
    method = 'contains';
    bitmask = 1;
  }

  rocking:
  while ((node = node && node.parentNode)) {
    for (var i = nodes.length; i--;) {
      if ((node[method](nodes[i]) & bitmask) !== bitmask)
        continue rocking;
    }
    return node;
  }

  return undefined;
}

jQuery.fn.commonAncestor = function() {
  return $(getCommonAncestor.apply(null, this));
};

a = document.getElementById("a"); b = document.getElementById("b");
c = document.getElementById("c"); d = document.getElementById("d");
prompt(
  'native: '+ getCommonAncestor(document.querySelectorAll("#a, #b, #c, #d")).id,
  'jQuery: '+ $('#a, #b, #c, #d').commonAncestor().attr('id')
);