How to find with javascript if element exists in DOM or it's virtual (has been just created by createElement) -
i'm looking way find if element referenced in javascript has been inserted in document.
lets illustrate case following code:
var elem = document.createelement('div'); // element has not been inserted in document, i.e. not present document.getelementbytagname('body')[0].appendchild(elem); // element can found in dom tree
jquery has :visible selector, won't give accurate result when need find invisible element has been placed somewhere in document.
here's easier method uses standard node.contains dom api check in element in dom:
document.body.contains(my_element);
cross-browser note: document object in ie not have contains()
method - ensure cross-browser compatibility, use document.body.contains()
instead. (or document.head.contains if you're checking elements link, script, etc)
notes on using specific document
reference vs node-level ownerdocument
:
someone raised idea of using my_element.ownerdocument.contains(my_element)
check node's presence in document. while can produce intended result (albeit, more verbosity necessary in 99% of cases), can lead unexpected results, depending on use-case. let's talk why:
if dealing node resides in separate document, 1 generated document.implementation.createhtmldocument()
, <iframe>
document, or html import document, , use node's ownerdocument
property check presence in think main, visually rendered document
, in world of hurt.
the node property ownerdocument
pointer whatever current document node resides in. every use-case of contains
involves checking specific document
node's presence. have 0 guarantee ownerdocument
same document want check - know that. danger of ownerdocument
may introduce number of ways reference, import, or generate nodes reside in other documents. if so, , have written code rely on ownerdocument
's relative inference, code may break. ensure code produces expected results, should compare against specifically referenced document
intend check, not trust relative inferences ownerdocument
.
Comments
Post a Comment