How to get the type of DOM element using JavaScript ?

The task is to get the type of DOM element by having its object reference. Here we are going to use JavaScript to solve the problem. 

Approach 1: 

  • First take the reference of the DOM object to a variable(Here, In this example an array is made of IDs of the element, then select random ID and select that particular element).
  • Use .tagName property to get the element name.

Example 1: This example uses the approach discussed above.  

html




<!DOCTYPE html>
<html>
 
<body>
    <h1 id="h1" style="color:green;">
        w3wiki
    </h1>
    <p id="GFG_UP"></p>
    <button id="button" onclick="GFG_Fun()">
        click here
    </button>
    <p id="GFG_DOWN"></p>
    <script>
        let up = document.getElementById('GFG_UP');
        let down = document.getElementById('GFG_DOWN');
        let arr = ["h1", "GFG_UP", "button", "GFG_DOWN"];
        up.innerHTML =
            "Click on the button to check the type of element.";
 
        function GFG_Fun() {
            let id = arr[(Math.floor(Math.random() * arr.length))];
            down.innerHTML =
                "The type of element of id = '" + id + "' is "
                + document.getElementById(id).tagName;
        }
    </script>
</body>
</html>


Output: 

How to get the type of DOM element using JavaScript?

Approach 2:  

  • First take the reference of the DOM object to a variable(Here, In this example an array is made of IDs of the element, then select random ID from the array and select that particular element.
  • Use .nodeName property to get the element name.

Example 2: This example uses the approach discussed above. 

html




<!DOCTYPE html>
<html>
 
<body>
    <h1 id="h1" style="color:green;">
        w3wiki
    </h1>
    <p id="GFG_UP"></p>
    <button id="button" onclick="GFG_Fun()">
        click here
    </button>
    <p id="GFG_DOWN"></p>
    <script>
        let up = document.getElementById('GFG_UP');
        let down = document.getElementById('GFG_DOWN');
        let arr = ["h1", "GFG_UP", "button", "GFG_DOWN"];
        up.innerHTML =
            "Click on the button to check the type of element.";
 
        function GFG_Fun() {
            let id = arr[(Math.floor(Math.random() * arr.length))];
            down.innerHTML =
                "The type of element of id = '" + id + "' is "
                + document.getElementById(id).nodeName;
        }
    </script>
</body>
</html>


Output: 

How to get the type of DOM element using JavaScript?



Contact Us