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

前端 未结 14 1950
-上瘾入骨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:14

    This is a generalized take on lonesomeday's answer. Instead of only two elements it will take a full JQuery object.

    function CommonAncestor(jq) {
        var prnt = $(jq[0]);
        jq.each(function () { 
            prnt = prnt.parents().add(prnt).has(this).last(); 
        });
        return prnt;
    }
    

提交回复
热议问题