代码之家  ›  专栏  ›  技术社区  ›  roborourke

在javascript中找到两个DOM节点的第一个公共父节点的最佳方法是什么?

  •  1
  • roborourke  · 技术社区  · 16 年前

    我的问题是,但是在上下文中,我想检查selection对象,比较anchorNode和focusNode,如果它们不同,那么找到第一个公共父元素。

    var selected = window.getSelection();
    var anchor = selection.anchorNode;
    var focus = selection.focusNode;
    
    if ( anchor != focus ) {
       // find common parent...
    }
    
    3 回复  |  直到 16 年前
        1
  •  6
  •   Alsciende    16 年前

    如果没有JS库,我会尝试这样的方法:

    function findFirstCommonAncestor(nodeA, nodeB, ancestorsB) {
        var ancestorsB = ancestorsB || getAncestors(nodeB);
        if(ancestorsB.length == 0) return null;
        else if(ancestorsB.indexOf(nodeA) > -1) return nodeA;
        else if(nodeA == document) return null;
        else return findFirstCommonAncestor(nodeA.parentNode, nodeB, ancestorsB);
    }
    

    function getAncestors(node) {
        if(node != document) return [node].concat(getAncestors(node.parentNode));
        else return [node];
    }
    
    if(Array.prototype.indexOf === undefined) {
        Array.prototype.indexOf = function(element) {
            for(var i=0, l=this.length; i<l; i++) {
                if(this[i] == element) return i;
            }
            return -1;
        };
    }
    

    然后你可以打电话 findFirstCommonAncestor(myElementA, myElementB) .

        2
  •  2
  •   cletus    16 年前

    这种方法相当简单:

    var fp = $(focus).parents();
    var ap = $(anchor).parents();
    for (var i=0; i<ap.length; i++) {
      if (fp.index(ap[i]) != -1) {
        // common parent
      }
    }
    

    循环通过 parents() 另一个使用 index() 直到你找到匹配的。

        3
  •  1
  •   kennebec    16 年前

    document.commonParent= function(a, b){
     var pa= [], L;
     while(a){
      pa[pa.length]=a;
      a= a.parentNode;
     }
     L=pa.length;
     while(b){  
      for(var i=0; i<L; i++){
       if(pa[i]==b) return b;
      }
      b= b.parentNode;
     }
    }