Open In App

How to Check if element exists in the visible DOM in JavaScript ?

This article will show you how to check whether an element exists in the visible DOM or not. For that purpose, there are several methods used but we’re going to look at a few of them.

Example 1: In this example, the element is searched by document.getElementById(‘Id’) and !! operator is used before the selector to get the boolean result.






<!DOCTYPE HTML>
<html>
  
<head>
    <title>
        Check if element exists in the 
        visible DOM in JavaScript
    </title>
  
    <style>
        body {
            text-align: center;
        }
  
        h1 {
            color: green;
        }
    </style>
</head>
  
<body>
    <h1 id="heading-content">
        GeeksforGeeks
    </h1>
  
    <p>Check if an Element exists in visible DOM</p>
  
    <button onclick="myFunc()">
        Click Here
    </button>
      
    <p id="result"></p>
  
    <script>
        let res = document.getElementById("result");
          
        let id = document.getElementById("heading-content").id;
  
        function myFunc() {
            let element = !!document.getElementById(id);
  
            let ans = '';
              
            if (element) {
                ans = "Element of id = '" + id +
                    "' exists in visible DOM.";
            } else {
                ans = "Element of id = '" + id +
                    "' not exists in visible DOM.";
            }
            res.innerHTML = ans;
        
    </script>
</body>
  
</html>

Output:



Example 2: In this example, the element is searched by document.getElementsByClassName(‘className’) and length property is used to check whether variable contains results or not.




<!DOCTYPE HTML>
<html>
  
<head>
    <title>
        JavaScript Check if element 
        exists in the visible DOM
    </title>
  
    <style>
        body {
            text-align: center;
        }
  
        h1 {
            color: green;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
  
    <p id="GFG_UP" class="para">
        Check if an Element exists 
        in visible DOM
    </p>
  
    <button onclick="myFunc()">
        Click Here
    </button>
  
    <p id="result" class="para"></p>
  
    <script>
        let res = document.getElementById("result");
  
        let className = 'para';
  
        function myFunc() {
            let element = 
                document.getElementsByClassName(className);
  
            let ans = '';
  
            if (element.length > 0) {
                ans = "Element of className = '" + className +
                    "' exists in visible DOM.";
            } else {
                ans = "Element of className = '" + className +
                    "' not exists in visible DOM.";
            }
              
            res.innerHTML = ans;
        
    </script>
</body>
  
</html>

Output:


Article Tags :