I'm looking for a way to find if element referenced in javascript has been inserted in the document.
Lets illustrate a case with following code:
var elem = document.createElement('div');
// Element has not been inserted in the document, i.e. not present
document.getElementByTagName('body')[0].appendChild(elem);
// Element can now be found in the DOM tree
Jquery has :visible selector, but it won't give accurate result when I need to find that invisible element has been placed somewhere in the document.
Use compareDocumentPosition to see if the element is contained inside
document
. PPK has browser compatibility details and John Resig has a version for IE.You can also use
jQuery.contains
:Here's an easier method that uses the standard Node.contains DOM API to check in an element is currently in the DOM:
CROSS-BROWSER NOTE: the document object in IE does not have a
contains()
method - to ensure cross-browser compatibility, usedocument.body.contains()
instead. (or document.head.contains if you're checking for elements like link, script, etc)Notes on using a specific
document
reference vs Node-levelownerDocument
:Someone raised the idea of using
MY_ELEMENT.ownerDocument.contains(MY_ELEMENT)
to check for a node's presence in the document. While this can produce the intended result (albeit, with more verbosity than necessary in 99% of cases), it can also lead to unexpected results, depending on use-case. Let's talk about why:If you are dealing with a node that currently resides in an separate document, like one generated with
document.implementation.createHTMLDocument()
, an<iframe>
document, or an HTML Import document, and use the node'sownerDocument
property to check for presence in what you think will be your main, visually rendereddocument
, you will be in a world of hurt.The node property
ownerDocument
is simply a pointer to whatever current document the node resides in. Almost every use-case ofcontains
involves checking a specificdocument
for a node's presence. You have 0 guarantee thatownerDocument
is the same document you want to check - only you know that. The danger ofownerDocument
is that someone may introduce any number of ways to reference, import, or generate nodes that reside in other documents. If they do so, and you have written your code to rely onownerDocument
's relative inference, your code may break. To ensure your code always produces expected results, you should only compare against the specifically referenceddocument
you intend to check, not trust relative inferences likeownerDocument
.The safest way is to test directly whether the element is contained in the document:
Do this: