[javascript] How can I check if an element exists in the visible DOM?

How do you test an element for existence without the use of the getElementById method?

I have set up a live demo for reference. I will also print the code on here as well:

<!DOCTYPE html>
<html>
<head>
    <script>
    var getRandomID = function (size) {
            var str = "",
                i = 0,
                chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
            while (i < size) {
                str += chars.substr(Math.floor(Math.random() * 62), 1);
                i++;
            }
            return str;
        },
        isNull = function (element) {
            var randomID = getRandomID(12),
                savedID = (element.id)? element.id : null;
            element.id = randomID;
            var foundElm = document.getElementById(randomID);
            element.removeAttribute('id');
            if (savedID !== null) {
                element.id = savedID;
            }
            return (foundElm) ? false : true;
        };
    window.onload = function () {
        var image = document.getElementById("demo");
        console.log('undefined', (typeof image === 'undefined') ? true : false); // false
        console.log('null', (image === null) ? true : false); // false
        console.log('find-by-id', isNull(image)); // false
        image.parentNode.removeChild(image);
        console.log('undefined', (typeof image === 'undefined') ? true : false); // false ~ should be true?
        console.log('null', (image === null) ? true : false); // false ~ should be true?
        console.log('find-by-id', isNull(image)); // true ~ correct but there must be a better way than this?
    };
    </script>
</head>
<body>
    <div id="demo"></div>
</body>
</html>

Basically the above code demonstrates an element being stored into a variable and then removed from the DOM. Even though the element has been removed from the DOM, the variable retains the element as it was when first declared. In other words, it is not a live reference to the element itself, but rather a replica. As a result, checking the variable's value (the element) for existence will provide an unexpected result.

The isNull function is my attempt to check for an elements existence from a variable, and it works, but I would like to know if there is an easier way to accomplish the same result.

PS: I'm also interested in why JavaScript variables behave like this if anyone knows of some good articles related to the subject.

This question is related to javascript dom variables element exists

The answer is


This code works for me, and I didn't have any issues with it.


    if(document.getElementById("mySPAN")) {
        // If the element exists, execute this code
        alert("Element exists");
    }
    else {
        // If the element does not exist execute this code
        alert("Element does not exists");
    }


You can also use jQuery.contains, which checks if an element is a descendant of another element. I passed in document as the parent element to search because any elements that exist on the page DOM are a descendant of document.

jQuery.contains( document, YOUR_ELEMENT)

this condition chick all cases.

_x000D_
_x000D_
function del() {_x000D_
//chick if dom has this element _x000D_
//if not true condition means null or undifind or false ._x000D_
_x000D_
if (!document.querySelector("#ul_list ")===true){_x000D_
_x000D_
// msg to user_x000D_
    alert("click btn load ");_x000D_
_x000D_
// if console chick for you and show null clear console._x000D_
    console.clear();_x000D_
_x000D_
// the function will stop._x000D_
    return false;_x000D_
}_x000D_
_x000D_
// if its true function will log delet ._x000D_
console.log("delet");_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_


csuwldcat's solution seems to be the best of the bunch, but a slight modification is needed to make it work correctly with an element that's in a different document than the JavaScript code is running in, such as an iframe:

YOUR_ELEMENT.ownerDocument.body.contains(YOUR_ELEMENT);

Note the use of the element's ownerDocument property, as opposed to just plain old document (which may or may not refer to the element's owner document).

torazaburo posted an even simpler method that also works with non-local elements, but unfortunately, it uses the baseURI property, which is not uniformly implemented across browsers at this time (I could only get it to work in the WebKit-based ones). I couldn't find any other element or node properties that could be used in a similar fashion, so I think for the time being the above solution is as good as it gets.


jQuery solution:

if ($('#elementId').length) {
    // element exists, do something...
}

This worked for me using jQuery and did not require $('#elementId')[0] to be used.


All existing elements have parentElement set, except the HTML element!

function elExists (e) { 
    return (e.nodeName === 'HTML' || e.parentElement !== null);
};

Use querySelectorAll with forEach,

document.querySelectorAll('.my-element').forEach((element) => {
  element.classList.add('new-class');
});

as the opposite of:

const myElement = document.querySelector('.my-element');
if (myElement) {
  element.classList.add('new-class');
}

I prefer to use the node.isConnected property (Visit MDN).

Note: This will return true if the element is appended to a ShadowRoot as well, which might not be everyone's desired behaviour.

Example:

const element = document.createElement('div');
console.log(element.isConnected); // Returns false
document.body.append(element);
console.log(element.isConnected); // Returns true

Use getElementById() if it's available.

Also, here's an easy way to do it with jQuery:

if ($('#elementId').length > 0) {
  // Exists.
}

And if you can't use third-party libraries, just stick to base JavaScript:

var element =  document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
  // Exists.
}

A simple solution with jQuery:

$('body').find(yourElement)[0] != null

From Mozilla Developer Network:

This function checks to see if an element is in the page's body. As contains() is inclusive and determining if the body contains itself isn't the intention of isInPage, this case explicitly returns false.

function isInPage(node) {
  return (node === document.body) ? false : document.body.contains(node);
}

node is the node we want to check for in the <body>.


Another option is element.closest:

element.closest('body') === null

I simply do:

if(document.getElementById("myElementId")){
    alert("Element exists");
} else {
    alert("Element does not exist");
}

It works for me and had no issues with it yet...


  • If an element is in the DOM, its parents should also be in
  • And the last grandparent should be the document

So to check that we just loop unto the element's parentNode tree until we reach the last grandparent

Use this:

/**
 * @param {HTMLElement} element - The element to check
 * @param {boolean}     inBody  - Checks if the element is in the body
 * @return {boolean}
 */
var isInDOM = function(element, inBody) {
    var _ = element, last;

    while (_) {
        last = _;
        if (inBody && last === document.body) { break;}
        _ = _.parentNode;
    }

    return inBody ? last === document.body : last === document;
};


I liked this approach:

var elem = document.getElementById('elementID');

if (elem)
    do this
else
    do that

Also

var elem = ((document.getElementById('elemID')) ? true:false);

if (elem)
    do this
else
    do that

Using the Node.contains DOM API, you can check for the presence of any element in the page (currently in the DOM) quite easily:

document.body.contains(YOUR_ELEMENT_HERE);

CROSS-BROWSER NOTE: the document object in Internet Explorer does not have a contains() method - to ensure cross-browser compatibility, use document.body.contains() instead.


Check if the element is a child of <html> via Node::contains():

const div = document.createElement('div');
document.documentElement.contains(div); //-> false

document.body.appendChild(div);
document.documentElement.contains(div); //-> true

I've covered this and more in is-dom-detached.


Check element exist or not

const elementExists = document.getElementById("find-me");
if(elementExists){
    console.log("have this element");
}else{
    console.log("this element doesn't exist");
}

Use this command below to return whether or not the element exists in the DOM:

return !!document.getElementById('myElement');

Instead of iterating parents, you can just get the bounding rectangle which is all zeros when the element is detached from the DOM:

function isInDOM(element) {
    if (!element)
        return false;
    var rect = element.getBoundingClientRect();
    return (rect.top || rect.left || rect.height || rect.width)?true:false;
}

If you want to handle the edge case of a zero width and height element at zero top and zero left, you can double check by iterating parents till the document.body:

function isInDOM(element) {
    if (!element)
        return false;
    var rect = element.getBoundingClientRect();
    if (element.top || element.left || element.height || element.width)
        return true;
    while(element) {
        if (element == document.body)
            return true;
        element = element.parentNode;
    }
    return false;
}

// This will work prefectly in all :D
function basedInDocument(el) {

    // This function is used for checking if this element in the real DOM
    while (el.parentElement != null) {
        if (el.parentElement == document.body) {
            return true;
        }
        el = el.parentElement; // For checking the parent of.
    } // If the loop breaks, it will return false, meaning
      // the element is not in the real DOM.

    return false;
}

Try the following. It is the most reliable solution:

window.getComputedStyle(x).display == ""

For example,

var x = document.createElement("html")
var y = document.createElement("body")
var z = document.createElement("div")
x.appendChild(y);
y.appendChild(z);

z.style.display = "block";

console.log(z.closest("html") == null); // 'false'
console.log(z.style.display); // 'block'
console.log(window.getComputedStyle(z).display == ""); // 'true'

A simple way to check if an element exist can be done through one-line code of jQuery.

Here is the code below:

if ($('#elementId').length > 0) {
    // Do stuff here if the element exists
} else {
    // Do stuff here if the element does not exist
}

You could just check to see if the parentNode property is null.

That is,

if(!myElement.parentNode)
{
    // The node is NOT in the DOM
}
else
{
    // The element is in the DOM
}

As I landed up here due to the question. Few of the solutions from above don't solve the problem. After a few lookups, I found a solution on the internet that provided if a node is present in the current viewport where the answers I tried solves of it's present in the body or not.

function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

isInViewport(document.querySelector('.selector-i-am-looking-for'));

The snippet is taken from HERE to keep as a backup as the links may be unavailable after some time. Check the link for an explanation.

And, didn't intend to post in the comment, as in most cases, they are ignored.


The easiest solution is to check the baseURI property, which is set only when the element is inserted in the DOM, and it reverts to an empty string when it is removed.

_x000D_
_x000D_
var div = document.querySelector('div');_x000D_
_x000D_
// "div" is in the DOM, so should print a string_x000D_
console.log(div.baseURI);_x000D_
_x000D_
// Remove "div" from the DOM_x000D_
document.body.removeChild(div);_x000D_
_x000D_
// Should print an empty string_x000D_
console.log(div.baseURI);
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to element

How can I loop through enum values for display in radio buttons? How to count items in JSON data Access multiple elements of list knowing their index Getting Index of an item in an arraylist; Octave/Matlab: Adding new elements to a vector add item in array list of android GetElementByID - Multiple IDs Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence? Check if one list contains element from the other How to get the focused element with jQuery?

Examples related to exists

Select rows which are not present in other table How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error? Check if record exists from controller in Rails sql: check if entry in table A exists in table B How to exclude records with certain values in sql select SQL - IF EXISTS UPDATE ELSE INSERT INTO Linq select objects in list where exists IN (A,B,C) PL/pgSQL checking if a row exists How to Check if value exists in a MySQL database MongoDB: How to query for records where field is null or not set?