js--求两个HTML的公共结点

在微薄上看到大家都在讨论这个问题...具体讨论可以看:http://weibo.com/1196343093/zrkFOna49

感觉跟链表求公共结点差不多原理,写了个代码:

var isCommon = function(aNode,bNode,deepth){
    while(deepth--){
        aNode = aNode.parentNode; 
    }
    while(aNode!=bNode){
        aNode = aNode.parentNode;
        bNode = bNode.parentNode;
    }
    return aNode; 
}

var findparent = function(a,b){
    var _a = a;
    var aDeep = 0; 
    while(_a){
        _a =  _a.parentNode;
        aDeep++; 
    }

    var bDeep = 0;
    var _b = b;
    while(_b){
        _b = _b.parentNode;
        bDeep++;
    }

    var dDeep;
    if(aDeep>bDeep){
        dDeep = aDeep - bDeep; 
    }else{
        dDeep = bDeep - aDeep; 
    }
    isCommon(aNode,bNode,dDeep);
}
下面这种解法感觉也很好:

function getCommonParent(el1, el2){

  if (el1 == el2) { 
    return el1.parentNode; 
  }

  function getParents(el){
    var parents = [];
    while(el) {
      parents.unshift(el);
      el = el.parentNode;
    }
    return parents;
  }

  var parents1 = getParents(el1);
  var parents2 = getParents(el2);

  var i = 0;
  var lenght = parents1.length > parents2.length ? parents1.length : parents2.length;

  while(i < lenght && parents1[i+1] == parents2[i+1]){
    i++;
  }

  return parents1[i];
}

你可能感兴趣的:(js--求两个HTML的公共结点)