簡體   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