Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 615
mpontus Avatar asked Apr 27 '10 05:04

mpontus


People also ask

How do you check if an element exists in the DOM JavaScript?

Use the getElementsByTagName to Check the Existence of an Element in DOM. The function getElementsByTagName() can return all elements with the specified tagName in DOM . The return of the function can be one or more elements or null if no element is found.

How do you know if an element is attached to DOM?

To check if an element is connected or attached to the DOM or the document object ( or otherwise called the context ), you can use the isConnected property in the element's object in JavaScript. The isConnected element property returns boolean true if it connected to the DOM ( document object) and false if not.

How do I check if a DOM element is empty?

You could just check the childNodes property of an element, which returns a Nodelist . If it's length is 0, then your element is empty.

How do you find whether element exists or not which should return as Boolean value?

The includes() method is one such method using which we can easily find out whether the expected value exists in the given array. There are various ways to use include() method. This method returns a Boolean value i.e. true if the value exists and false if it incorrect.


3 Answers

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 <iframe> document, or an HTML Import document, and use the node's ownerDocument property to check for presence in what you think will be your main, visually rendered document, 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 of contains involves checking a specific document for a node's presence. You have 0 guarantee that ownerDocument is the same document you want to check - only you know that. The danger of ownerDocument 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 on ownerDocument's relative inference, your code may break. To ensure your code always produces expected results, you should only compare against the specifically referenced document you intend to check, not trust relative inferences like ownerDocument.

like image 147
csuwldcat Avatar answered Nov 06 '22 13:11

csuwldcat


Do this:

var elem = document.createElement('div');
elem.setAttribute('id', 'my_new_div');

if (document.getElementById('my_new_div')) { } //element exists in the document.
like image 38
DexterW Avatar answered Nov 06 '22 15:11

DexterW


The safest way is to test directly whether the element is contained in the document:

function isInDocument(el) {
    var html = document.body.parentNode;
    while (el) {
        if (el === html) {
            return true;
        }
        el = el.parentNode;
    }
    return false;
}

var elem = document.createElement('div');
alert(isInDocument(elem));
document.body.appendChild(elem);
alert(isInDocument(elem));
like image 30
Tim Down Avatar answered Nov 06 '22 15:11

Tim Down