在实际开发中,很多时候需要知道某个节点是不是另一个节点的后代。很多浏览器提供了contains方法,如:

console.log(document.documentElement.contains(document.body));//输入ture

DOM3提供的compareDocumentPosition方法也可以判断元素位置关系,结果如下:

1  无关

2  居前

4  居后

8  包含

16  被包含

因此跨浏览器的contains写法如下:

function contains(refNode,otherNode){
    if(typeof refNode.contains ==='function'){
        return refNode.contains(otherNode);
    }else if(typeof refNode.compareDocumentPosition ==='function'){
        return !!(refNode.compareDocumentPosition(otherNode)&16);
    }else{
        var node=otherNode.parentNode;
        do{
            if(node===refNode){
                return true;
            }
        }while(parentNode!=null);
        return false;
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-13
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-06-11
  • 2021-11-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案