How to check if element exists in the visible DOM?

DOMObject Oriented ProgrammingProgramming

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.


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

const elem = document.querySelector('#test');

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

Published on 27-Nov-2019 15:11:59