繁体   English   中英

HTML元素附加到文档

[英]HTML element is attached to a document

使用removeChild()从DOM中删除元素时,对元素的引用仍然存在,但元素不再在DOM中。
如何知道HTML元素(或其父元素)是否仍附加到文档?

Node.prototype.contains()就是答案:

if(document.body.contains(yourElement)) {
    // Yep, it's attached.
}

兼容性:IE5 +

继续检查元素的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中测试过。

该页面上也有其他选择。

对于较新的浏览器(没有IE支持),您可以使用Node.isConnected ,它是Node上的属性并返回一个布尔值。

Mozilla Node.isConnected

document.querySelectorAll('#myElement').isConnected;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM