How to check if element exists in the visible DOM?

We can use the Node.contains method to do this check. The Node.contains() method returns a Boolean value indicating whether a node is a descendant of a given node, i.e. the node itself, one of its direct children (childNodes), one of the children's direct children, and so on.

Example

For example, you are looking for an element with id test, you can use the following −

const elem = document.querySelector('#test');
console.log(document.body.contains(elem));

This will log true or false based on whether the element is present in the visible DOM.

Updated on: 2019-11-27T10:42:43+05:30

819 Views

Advertisements