jQuery.commonAncestor plugin
Usage
$(nodes, to, find, common, ancestor, of).commonAncestor()
Credits
See also: test case, StackExchange origin
$(nodes, to, find, common, ancestor, of).commonAncestor()
See also: test case, StackExchange origin
| 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)); | |
| }; |