节点间"包含"关系的访问
判断2个节点间是否存在包含关系,即是否存在父子之间的关系,我们可以使用:
elA.contains(elB)方法,如果elA是elB的祖先,则返回true.
//判断 <html>元素是否包含<body>元素alert(document.documentElement.contains(document.body)); //true
IE,Chrome,Opera8+,Safari3+支持该属性,Firefox不支持该方法,不过,它提供了另外一个方法:
elA.compareDocumentPosition(elB),它返回一个"位掩码"来表示节点间的关系。返回值如下:
?
//例如://因为 <body>在<html>之后,且被包含,所以值为 4 + 16 = 20;alert(document.documentElement.contains(document.body)); //20
?因此,跨浏览器的包含判断函数如下:
function contains(refNode, otherNode){if (typeof refNode.contains == 'function' && (!client.engine.webkit || client.engine.webkit >= 522)){ 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; } else { node = node.parentNode; } } while (node !== null); return false;}}?
?
?