Create a gist now

Instantly share code, notes, and snippets.

`jQuery#commonAncestor()` and `getCommonAncestor(node /*, node2, node3, ... nodeN */)`
function getCommonAncestor(node /*, node2, node3, ... nodeN */) {
if (!node || node.nodeType !== 1)
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));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment