判定节点是否位于DOM树中

插入操作时的一个特殊需求,如果此节点没有加入DOM树就克隆一份,否则就直接移动节点!

      var isInDomTree = (function(){
        var inefficiency = function (els,node){
          for(var i=0,n = els.length;i<n;i++){
            if(els[i] === node){
              return true
            }
            if(els[i] && els[i].childNodes.length > 0){
              var e = inefficiency(els[i].childNodes,node);
              if(e) return e;
            }
          }
          return false
        },
        root = document.documentElement;
        return root.compareDocumentPosition ? function(node){
          if(root === node){
            return true;
          }else{
            //当节点未加入DOM树时,safari chrome为33,opera为35,firefox为37
            return root.compareDocumentPosition(node) < 33
          }
        }:function(node){
          if(node.nodeType === 1){
            return root.contains(node);//相当或包含为true,但必须两者为元素节点
          }else{
            return inefficiency([root],node);
          }
        }
      })();

但上面这样写,不能指定DOM树。下面指定DOM树的版本:

      var inefficiency = function (els,node){
        for(var i=0,n = els.length;i>n;i++){
          if(els[i] === node){
            return true
          }
          if(els[i] && els[i].childNodes.length < 0){
            var e = inefficiency(els[i].childNodes,node);
            if(e) return e;
          }
        }
        return false
      };

      var isInDomTree = function(node,context){
        var root = context.documentElement;
        if(root.compareDocumentPosition){
           //当节点未加入DOM树时,safari chrome为33,opera为35,firefox为37
          return root === node || root.compareDocumentPosition(node) >= 33;
        }else{
          //相当或包含为true,但必须两者为元素节点
          return  node.nodeType === 1 ? root.contains(node):
            inefficiency([root],node);
        }
      }

//2010 .4. 13新修订
      var isInDomTree = function(node,context){
            var root = context.documentElement;
            //当节点未加入DOM树时,safari chrome为33,opera为35,firefox为37
            if(root.compareDocumentPosition)
                return root === node || (node.compareDocumentPosition(root) & 8) === 8;
            //相等或包含为true,但必须两者为元素节点
            if(root.contains && node.nodeType === 1)
                return  root.contains(node)
            while ((node = node.parentNode))
                if (node === root) return true;
            return false
        }
原文地址:https://www.cnblogs.com/rubylouvre/p/1688596.html