ChatGPT解决这个技术问题 Extra ChatGPT

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.

Actually it is a live reference to the element itself, it's just not in a document any more. That functionality is required because you can actually pull an element out of the DOM and then put it back in later with all event handlers/etc still attached to it. As for why JS variables act like that? Because it would be incredibly annoying if they didn't. JS only deletes variables when you no longer have ANY references to them. The language has no way of knowing which references you deem important and which you think are worthless.
@cwolves Interesting. I've encountered this many times before and never really thought much of it. In fact, in my current project, I'm saving elements in an array before I make any changes to them, just in case I want to revert the changes.
Garbage collection runs from time to time and deletes everything it thinks it can. It seems pretty lousy in most browsers, but is getting better as developers realise that some browsers run for days or weeks between restarts, so good garbage collection is vital for browser performance. Web developers can help by deleting properties (and hence references to things in memory) that are no longer required.
@JustinBull be careful with storing copies of the elements to revert. When storing a DOM element in an array, a reference to the DOM element is stored, not a copy, so changes made to the DOM element will be reflected when referencing the array's element. This is the case with all objects in javascript (variables of type 'object').

P
Peter Mortensen

It seems some people are landing here, and simply want to know if an element exists (a little bit different to the original question).

That's as simple as using any of the browser's selecting method, and checking it for a truthy value (generally).

For example, if my element had an id of "find-me", I could simply use...

var elementExists = document.getElementById("find-me");

This is specified to either return a reference to the element or null. If you must have a Boolean value, simply toss a !! before the method call.

In addition, you can use some of the many other methods that exist for finding elements, such as (all living off document):

querySelector()/querySelectorAll()

getElementsByClassName()

getElementsByName()

Some of these methods return a NodeList, so be sure to check its length property, because a NodeList is an object, and therefore truthy.

For actually determining if an element exists as part of the visible DOM (like the question originally asked), Csuwldcat provides a better solution than rolling your own (as this answer used to contain). That is, to use the contains() method on DOM elements.

You could use it like so...

document.body.contains(someReferenceToADomElement);

Exactly what i was looking for! So obviously lol, why didn't I think of that. Also, do you know of any good articles that explain why variables act like this?
Even shorter: var elementInDom = function( el ) { while ( el = el.parentNode ) if ( el === document ) return true; return false; }
@ButtleButkus Read the actual question. That solution you used doesn't make sense as getElementById() will return a reference to a DOM element or null, therefore, using typeof (especially on the RHS) is wrong (if it weren't defined, the LHS condition would throw a ReferenceError).
Is there any reason to use this over what was posted below: document.body.contains() which seems to have very good browser support?
@Jonz Removed the old answer part, don't forget to go and vote up csuwldcat
P
Peter Mortensen

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.
}

For the project I'm working on, I'm not able to use a library. Good-ol' fashion raw code only. I'm aware of that jQuery method, but it does not work on elements not wrapped in the jQuery container. For example, $('#elementId')[0].length would not produce the same result.
Is there any good reason for such a complicated if statement in the second code example? Why not simply if (element) {}? When element is undefined or null then this expression is false. If element is a DOM element then the expression is true.
@kayahr It is far too complicated. getElementById() is spec'd to return null if it didn't find the element, so checking for a truthy returned value is all that's needed.
I think that's just common sense.
getElementById should never return undefined. In any case, the element != null check would pick this up.
P
Peter Mortensen

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.


This seems like the ultimate answer to this problem...and its support, if MDN is to be believed is quite good.
This is the best answer. Note that just checking document.contains() should be enough.
@csuwldcat It worked for me, at least in Chrome with document.contains(document.documentElement). document does have Node on its prototype chain, as far as I can tell (document->HTMLDocument->Document->Node)
This is indeed the best answer: - it's a web standard - it's very well supported (somewhat surprisingly it doesn't appear in Firefox until version 9, I'm guessing because it was a non-standard function invented in IE that wasn't standardized until later) - it must be the fastest because it uses a single call to a native API
@LeeSaxon The syntaxis is document.body.contains([selector]), i.e. document.body.contains(document.getElementById('div')
P
Peter Mortensen

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...


This has nothing to do with the original question though. The OP wants to know if a reference to a DOM element is part of the visible DOM or not.
This answer works well, but only when the element has an id. The better solution that answers the question How to check if element exists in the visible DOM? with any element, even elements without ids is to do document.body.contains(element).
@Edward This is something completely different to contains()
I get that. I was just suggesting in my comment that other answers are better and more suited to the question.
This won't check the visible DOM. Will check all the DOM
D
Doug Blank

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

Simplest solution... Easier than document.body.contains.
M
Mehan Alavi

Easiest way:

const cond = document.getElementById('elem') || false
if (cond) {
    //does
} else {
    //does not
}

If needed in strictly visible DOM, meaning not on entire page, use something like view-js (my lib so beat it up as much as you want)


<script src='https://view-js.glitch.me/view-main.js'></script>
<script>
elem = $sel('#myelem');
if (isVis(elem)) { //yes } else { //no }
</script>

function test() { pt = document.querySelector('#result') iv = document.querySelector('#f') cond = document.querySelector('#'+iv.value) || false if (cond) { pt.innerText = 'Found!' } else { pt.innerText = 'Not found!' } } Enter an id to see if it exists:

I am a p tag. I will change depending on the result.


I am a div. My id is demo.


17 upvotes. My most ever!
P
Peter Mortensen

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 .


+1, does this work for (arbitrary) text nodes (or comment nodes) as well?
@NikosM. It should work in any html tag but I didn't test it.
Shouldn't the false be true?
If the node IS the document.body, surely the method should return true? I.e., return (node === document.body) || document.body.contains(node);
P
Peter Mortensen

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
}

I know this is an old question but this answer is exactly the kind of elegant simple solution to the question which I was looking for.
@poby: It might seem elegant but it isn't really doing what was requested. It only checks if the element has a parent element. This doesn't imply that the element is in the visible DOM because maybe the parent element is not connected to it.
One would have to go through all parent of parents to find out if last one is document. The other problem is it still could be outside of visible range or be covered or be not visible because of many other reasons.
An element could also have a parentNode only by virtue of having been appended to a document fragment.
@Eric An element which has no parent node can't be connected to the document , that's right. But on the other hand when element has a parent node then this does NOT automatically mean that the element is connected to the document because the parent node may be disconnected and this means all child elements are also disconnected. So this check is wrong and does not do what it says.
P
Peter Mortensen

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.

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


I didn't even know there was baseURI property on DOM nodes. What I like about this approach is that it uses a property of the element itself, which presumably means it would work even if the element is in a different document (e.g. an iframe). What I don't like about it is that it doesn't seem to work outside of Webkit.
Careful as this will throw the following error if the element is not in the document: Cannot read property 'baseURI' of null. Example: console.log(document.querySelector('aside').baseURI)
This method can't be used as it always prints the same string as of now.
Need a try catch for this method.
a
alex

jQuery solution:

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

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


Why is $('#elementId')[0] something to be avoided?
Been long I answered this, So, using $('#elementId')[0] I believe you are always indicating that the value will be at the 0th index. This way you are always checking for the 1st occuring element. What is there were multiple checkboxes with same name, so like a radio button. That time the .length will be helpful.
P
Peter Mortensen

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.


P
Peter Mortensen

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
}

P
Peter Mortensen

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;
}

P
Peter Mortensen

Another option is element.closest:

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

P
Peter Mortensen

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");
    }


S
Steven Vachon

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.


a
andrewgu

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)

P
Peter Mortensen

A simple solution with jQuery:

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

...or $(document).find(yourElement).length !== 0
This exploits that null == undefined. The real returned value would be undefined. Comparing it against null is a bit weird.
P
Peter Mortensen
// 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;
}

In all what? All cases?
P
Peter Mortensen

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

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

Is it always "HTML"? Could it be "html"?
x.tagName or x.nodeName always in uppercase no mater how you write it in your code
s
silassare

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;
};


This might be the best answer as it does not cause any re-rendering in the DOM.
An explanation would be in order (respond by editing your answer, not here in comments).
O
Omar bakhsh

this condition chick all cases.

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


h
hatef

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

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

M
MD SHAYON

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");
}

P
Peter Mortensen

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');
}

s
ssi-anik

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.


P
Peter Mortensen

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

Why not just !! if you want a Boolean?
So, if the element doesn't have an id, then it's considered to be not in the DOM? I'd say this is wrong.