How to check if element exists in the visible DOM?

吃可爱长大的小学妹 提交于 2019-11-26 00:56:43

问题


How do you test an element for existence without the use of the getElementById method? I have setup 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 what the above code demonstrates is an element being stored into a variable and then removed from 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.


回答1:


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 spec'd 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);



回答2:


Why would you not 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 3rd-party libraries, just stick to base JavaScript:

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



回答3:


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 IE does not have a contains() method - to ensure cross-browser compatibility, use document.body.contains() instead




回答4:


I simply do:

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

Works for me and had no issues with it yet....




回答5:


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 .




回答6:


Could you just check to see if the parentNode property is null?

i.e.

if(!myElement.parentNode)
{
    //node is NOT on the dom
}
else
{
    //element is on the dom
}



回答7:


Easiest solution is to check the baseURI property, which is set only when the element is inserted in the DOM, and 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);
<div></div>



回答8:


jQuery solution:

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

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




回答9:


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




回答10:


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

Here is the code below:

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



回答11:


instead of iterating parents you can just get the bounding rect which is all zeros when the element is detached from 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;
}



回答12:


Another option element.closest:

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



回答13:


Simple solution with jQuery

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



回答14:


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)



回答15:


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.




回答16:


// this will work prefect in all :D     
function basedInDocument(el) {
        // this function use for checking if this element in a real DOM
        while (el.parentElement != null) {
            if (el.parentElement == document.body) {
                return true;
            }
            el = el.parentElement; // for check parent of 
        } // if loop break will return false mean element not in real DOM
        return false;
    }



回答17:


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



回答18:


Use this:

var isInDOM = function(element, inBody) {
    var _ = element, last;

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

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



回答19:


Use querySelectorAll with forEach:

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

as the opposite to:

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



回答20:


try this, this is the most reliable solution:

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

ie:

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



回答21:


all existing elements have parentElement set except HTML element!

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


来源:https://stackoverflow.com/questions/5629684/how-to-check-if-element-exists-in-the-visible-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!