How to find with javascript if element exists in DOM or it's virtual (has been just created by createElement)

后端 未结 6 1551
庸人自扰
庸人自扰 2021-01-12 04:36

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:

v         


        
6条回答
  •  长发绾君心
    2021-01-12 05:00

    Here's an easier method that uses the standard Node.contains DOM API to check in an element is currently in the DOM:

    document.body.contains(MY_ElEMENT);
    

    CROSS-BROWSER NOTE: the document object in IE does not have a contains() method - to ensure cross-browser compatibility, use document.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-level ownerDocument:

    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