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