Home >Web Front-end >JS Tutorial >How Can I Determine if an Element is Present in the Visible DOM?
Finding an element in the DOM using its ID is a common task in JavaScript. However, what if you need to check for the existence of an element without using this method?
When an element is removed from the DOM, its reference in a JavaScript variable still exists. This can lead to unexpected results when checking for element existence using typeof or === null.
The isNull() function attempts to circumvent this issue by temporarily setting a random ID on the element, finding it using getElementById(), and then removing the temporary ID. This approach returns true if the element is not found in the DOM and false if it is found.
If the goal is simply to check if an element exists (regardless of its visibility), a simpler approach is to use any of the browser's element selection methods:
<code class="javascript">var elementExists = document.getElementById("find-me");</code>
For a boolean value, you can use !! before the selection method call. Additionally, methods like querySelector() and getElementsByTagName() can be used.
To specifically check if an element exists in the visible DOM, the contains() method can be used:
<code class="javascript">document.body.contains(someReferenceToADomElement);</code>
This method returns true if the element is present in the DOM and false otherwise.
The above is the detailed content of How Can I Determine if an Element is Present in the Visible DOM?. For more information, please follow other related articles on the PHP Chinese website!