"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Determine if an Element is Present in the Visible DOM?

How Can I Determine if an Element is Present in the Visible DOM?

Published on 2024-10-31
Browse:358

How Can I Determine if an Element is Present in the Visible DOM?

How to Check if an Element Exists 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?

Identifying Invisible Elements

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.

Current Approach

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.

Simplification for Existence Check

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:

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

For a boolean value, you can use !! before the selection method call. Additionally, methods like querySelector() and getElementsByTagName() can be used.

Checking Visibility in the DOM

To specifically check if an element exists in the visible DOM, the contains() method can be used:

document.body.contains(someReferenceToADomElement);

This method returns true if the element is present in the DOM and false otherwise.

Release Statement This article is reprinted at: 1729519995 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3