Home >Web Front-end >JS Tutorial >How to Check if an Element Exists in the Visible DOM Without Using getElementById
How to Check Element Existence in the Visible DOM
To determine if an element exists in the visible DOM without using getElementById, consider the following alternatives:
Checking Presence in Document body:
As suggested by Csuwldcat, the contains() method of DOM elements can be employed to check if an element is a descendant of the document body. This method returns a Boolean value indicating if the element is part of the visible DOM.
<code class="js">document.body.contains(elementReference);</code>
Using other Element Selection Methods:
Other element selection methods, such as querySelector(), querySelectorAll(), and getElementsByClassName(), can be used to find elements based on specific criteria. If the resulting element reference or NodeList has a length of 0, the element does not exist.
For example, to check for an element with the id "find-me":
<code class="js">var elementExists = !!document.getElementById("find-me");</code>
Note: querySelector() and querySelectorAll() return the first matching element or a NodeList, respectively. getElementsByClassName() returns a NodeList. So, checking the length property for NodeLists is necessary to determine if an element exists.
Custom Function to Check Element Presence:
The provided isNull function can be used to check for element existence by temporarily assigning a random ID, searching for the element with the ID, and then removing the random ID. This approach effectively verifies if the element exists in the DOM.
Related Resources for JavaScript Variable Behavior:
The above is the detailed content of How to Check if an Element Exists in the Visible DOM Without Using getElementById. For more information, please follow other related articles on the PHP Chinese website!