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

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

    Somewhat late to the party, here's a JavaScript ES6 version that uses Array.prototype.reduce() and Node.contains(), and can take any number of elements as parameters:

    function closestCommonAncestor(...elements) {
        const reducer = (prev, current) => current.parentElement.contains(prev) ? current.parentElement : prev;
        return elements.reduce(reducer, elements[0]);
    }
    
    const element1 = document.getElementById('element1');
    const element2 = document.getElementById('element2');
    const commonAncestor = closestCommonAncestor(element1, element2);
    

提交回复
热议问题