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

前端 未结 14 1974
-上瘾入骨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条回答
  •  猫巷女王i
    2020-11-30 04:14

    Somewhat late to the party, but here's an elegant jQuery solution (since the question is tagged jQuery) -

    /**
     * Get all parents of an element including itself
     * @returns {jQuerySelector}
     */
    $.fn.family = function() {
        var i, el, nodes = $();
    
        for (i = 0; i < this.length; i++) {
            for (el = this[i]; el !== document; el = el.parentNode) {
                nodes.push(el);
            }
        }
        return nodes;
    };
    
    /**
     * Find the common ancestors in or against a selector
     * @param selector {?(String|jQuerySelector|Element)}
     * @returns {jQuerySelector}
     */
    $.fn.common = function(selector) {
        if (selector && this.is(selector)) {
            return this;
        }
        var i,
                $parents = (selector ? this : this.eq(0)).family(),
                $targets = selector ? $(selector) : this.slice(1);
        for (i = 0; i < $targets.length; i++) {
            $parents = $parents.has($targets.eq(i).family());
        }
        return $parents;
    };
    
    /**
     * Find the first common ancestor in or against a selector
     * @param selector {?(String|jQuerySelector|Element)}
     * @returns {jQuerySelector}
     */
    $.fn.commonFirst = function(selector) {
        return this.common(selector).first();
    };
    

提交回复
热议问题