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

前端 未结 14 1965
-上瘾入骨i
-上瘾入骨i 2020-11-30 04:03

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

14条回答
  •  悲哀的现实
    2020-11-30 04:27

    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.)

提交回复
热议问题