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

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

    This doesn't require much code anymore to solve:

    steps:

    1. grab parent of node_a
    2. if parent of node_a contains node_b return parent (in our code, the parent is referenced as node_a)
    3. if parent does not contain node_b we need to keep going up the chain
    4. end return null

    code:

    function getLowestCommonParent(node_a, node_b) {
        while (node_a = node_a.parentElement) {
            if (node_a.contains(node_b)) {
                return node_a;
            }
        }
    
        return null;
    }
    

提交回复
热议问题