当使用removeChild()
从DOM中删除元素时,对该元素的引用仍然存在,但该元素不再在DOM中。
如何知道HTML元素(或其父级)是否仍连接到文档?
当使用removeChild()
从DOM中删除元素时,对该元素的引用仍然存在,但该元素不再在DOM中。
如何知道HTML元素(或其父级)是否仍连接到文档?
Node#contains()
方法检查元素是否位于特定文档或其他元素内部:if(document.contains(yourElement)) {
// Yep, it's attached to the current document
}
或者使用 Node#isConnected
来检查它是否连接到 任何 文档:
if(yourElement.isConnected) {
// Yep, it's attached to any documents
}
Shadow DOM 内的元素注意事项:
.contains()
方法要求调用 getRootNode()
方法才能获取到位于主文档中最顶层的元素,需要进行递归操作: document.contains(yourElement.getRootNode().host)
.isConnected
属性即使元素没有连接到主 document
中,例如在一个不在当前文档中的 Shadow DOM 或 iframe 中,它也会返回 true
。对于较新的浏览器(不支持IE),您可以使用Node.isConnected
,这是Node
上的属性,返回一个布尔值。
document.querySelectorAll('#myElement').isConnected;
不断检查元素的parentNode,直到到达文档或遍历完所有节点。
function is_element_in_document ( element ) {
if (element === document) {
return true;
}
element = element.parentNode;
if (element) {
return is_element_in_document ( element );
}
return false;
}
parentNode
属性,如果它直接附加到文档,则为null
。如果没有这样的父元素,否则是对父元素的引用。null
,[Object HTMLBodyElement]
和null
。var elm = document.createElement("p");
alert(elm.parentNode);
document.body.appendChild(elm);
alert(elm.parentNode);
elm.parentNode.removeChild(elm);
alert(elm.parentNode);
removeChild
删除的元素,如果删除了父元素,则必须检查该父元素上的parentNode
属性。document
。function element_is_part_of_document(element) {
/* as long as the element is not document, and there is a parent element */
while (element != document && element.parentNode) {
/* jump to the parent element */
element = element.parentNode;
}
/* at this stage, the parent is found. If null, the uppermost parent element */
/* is not document, and therefore the element is not part of the document */
return element == document;
}
来自http://code.google.com/p/doctype-mirror/wiki/ArticleNodeContains:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
function contains(parent, descendant) {
return parent == descendant || Boolean(parent.compareDocumentPosition(descendant) & 16);
}
window.addEventListener("DOMContentLoaded", function() {
var p = document.getElementById("test");
//document.body.removeChild(p);
alert(contains(document, p));
}, false);
</script>
</head>
<body>
<p id="test">test</p>
</body>
</html>
我只在Opera浏览器上进行了测试。
该页面上也有其他替代方案。
Node.DOCUMENT_POSITION_CONTAINED_BY
,如https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition所述。此外,该方法不支持IE 8及以下版本。 - ug_
document.contains
在ie11下不起作用,但document.body.contains
可以。 - Nick Russler