Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an element exists in the visible DOM?

How do you test an element for existence without the use of the getElementById method?

I have set up 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 the above code demonstrates an element being stored into a variable and then removed from the 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.

like image 985
Justin Bull Avatar asked Apr 12 '11 02:04

Justin Bull


People also ask

How do you check if an element exists in the DOM?

Use the getElementsByTagName to Check the Existence of an Element in DOM. The function getElementsByTagName() can return all elements with the specified tagName in DOM . The return of the function can be one or more elements or null if no element is found.

How do you check if an element is visible on the screen?

Summary. Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.

How do I check if an element ID exists?

Approach 1: First, we will use document. getElementById() to get the ID and store the ID into a variable. Then compare the element (variable that store ID) with 'null' and identify whether the element exists or not.


2 Answers

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 specified 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); 
like image 95
alex Avatar answered Sep 22 '22 17:09

alex


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 third-party libraries, just stick to base JavaScript:

var element =  document.getElementById('elementId'); if (typeof(element) != 'undefined' && element != null) {   // Exists. } 
like image 36
Kon Avatar answered Sep 24 '22 17:09

Kon