HTML element is attached to a document

Issue

When an element is removed from the DOM using removeChild(), the reference to the element still exist but the element is no more in the DOM.
How to know if an HTML element (or its parents) is still attached to a document ?

Solution

From 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>

I only tested in Opera though.

There are alternatives on that page too.

Answered By – Shadow2531

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published