Karol Karol - 2 years ago 88
Javascript Question

Checking whether existing DOM element reference points to the element in the DOM

So i have a reference of an DOM element, which I know nothing about:

var div = somePieceOfCodeReturningDomElement();

I don't want to use a jQuery, or selectors and fetch element by its
or other attributes, it should be a Vanilla JS solution. I'm looking for something like this:

function isInTheDom(element) {
// checking

if (isInTheDom(div)) {
// yupi

It must also work in the case when an element was placed in the DOM, but was then removed. I don't know if it changes anything but it's a requirement.

Answer Source

I found the answer to the problem here:

Document and DocumentFragment nodes can never have a parent, so parentNode will always return null.

It also returns null if the node has just been created and is not yet attached to the tree.

So the function would look like this:

function isInTheDom(element) {
    return !!element.parentNode;

And it works well in the case when an element was attached to the DOM but then taken out.

If you want to check whether element is in the detached tree you may create a function like this:

function isInDetachedTree(element) {
    var parent;

    while (isInTheDom(element)) {
        element = element.parentNode;

    if (
        element.nodeType === Node.DOCUMENT_NODE ||
        element.nodeType === Node.DOCUMENT_FRAGMENT_NODE
    ) {
        return false;

    return true;

To test it go to https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild, open console and paste both functions and this code:

var el = document.getElementById('wiki-column-container');
var container = document.getElementById('content');

console.log('Removing #content element from DOM');

container = container.parentNode.removeChild(container);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download