Fra*_*ger 9 html javascript dom
当使用DOM从DOM中删除元素时,对元素removeChild()的引用仍然存在,但元素不再在DOM中.
如何知道HTML元素(或其父元素)是否仍附加到文档?
fre*_*nte 14
Node.prototype.contains() 是答案:
if(document.body.contains(yourElement)) {
// Yep, it's attached.
}
Run Code Online (Sandbox Code Playgroud)
兼容性:IE5 +
Que*_*tin 10
继续检查元素的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;
}
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
请再次注意,这仅适用于已删除的元素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;
}
Run Code Online (Sandbox Code Playgroud)
来自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>
Run Code Online (Sandbox Code Playgroud)
我只在Opera中测试过.
该页面上也有其他选择.
对于较新的浏览器(不支持IE),您可以使用Node.isConnected,这是on的属性,Node并返回布尔值。
document.querySelectorAll('#myElement').isConnected;
Run Code Online (Sandbox Code Playgroud)