Search code examples
javascriptjquery

How to find the nearest common ancestors of two or more nodes?


Users selects two or more elements in a HTML page. What I want to accomplish is to find those elements' common ancestors (so body node would be the common ancestor if none found before)?

P.S: It can be achieved with XPath but it is not a preferable option for me. Also it may be found with css selector parsing but I think it is a dirty method.


Solution

  • Try this:

    function get_common_ancestor(a, b)
    {
        $parentsa = $(a).parents();
        $parentsb = $(b).parents();
    
        var found = null;
    
        $parentsa.each(function() {
            var thisa = this;
    
            $parentsb.each(function() {
                if (thisa == this)
                {
                    found = this;
                    return false;
                }
            });
    
            if (found) return false;
        });
    
        return found;
    }
    

    Use it like this:

    var el = get_common_ancestor("#id_of_one_element", "#id_of_another_element");
    

    That's just rattled out pretty quickly, but it should work. Should be easy to amend if you want something slightly different (e.g. jQuery object returned instead of DOM element, DOM elements as arguments rather than IDs, etc.)