Categories
JavaScript Answers

How to Check if an Element Exists in the Visible DOM with JavaScript?

Spread the love

document.body.contains

We can use the document.body.contains method checks if an element is part of the visible DOM.

For instance, we can write the following HTML:

<div>  
  hello world  
</div>

And then we can check if the div is in the visible DOM by writing:

const div = document.querySelector('div')  
const isVisible = document.body.contains(div)  
console.log(isVisible)

We get the element with querySelector and pass it into the contains method.

And we see that the console log logs true if it’s visible on the page.

contains is available with anything other than Internet Explorer.

document.documentElement.contains

Instead document.body.contains , we can use document.documentElement.contains to do the same check.

For instance, we can write:

const div = document.querySelector('div')  
const isVisible = document.documentElement.contains(div)  
console.log(isVisible)

to do the check on the div.

And we should get the same result as before.

Check the parentNode Property

Another way to check if an element is in the visible DOM is to check if the parentNode property is truthy.

If it is, then we know the element is in the visible DOM.

For instance, we can write:

const div = document.querySelector('div')  
const isVisible = Boolean(div.parentNode)  
console.log(isVisible)

We just pass the div.parentNode property straight into the Boolean function to return true if it’s truthy and false otherwise.

And so we should see that the console log is true if we have the same HTML as in the first example.

Check the baseURI Property

Another property we can check to see if an element is in the visible DOM is in the baseURI property.

For instance, we can write:

const div = document.querySelector('div')  
const isVisible = Boolean(div.baseURI)  
console.log(isVisible)

to do the check.

If div.baseURI is truthy, then it’s in the DOM.

Otherwise, it’s not.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *