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

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

    Here's a pure JavaScript version that is a little more efficient.

    function parents(node) {
      var nodes = [node]
      for (; node; node = node.parentNode) {
        nodes.unshift(node)
      }
      return nodes
    }
    
    function commonAncestor(node1, node2) {
      var parents1 = parents(node1)
      var parents2 = parents(node2)
    
      if (parents1[0] != parents2[0]) throw "No common ancestor!"
    
      for (var i = 0; i < parents1.length; i++) {
        if (parents1[i] != parents2[i]) return parents1[i - 1]
      }
    }
    

提交回复
热议问题