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 using the approach discussed above.
html
< h1 id = "h1" style = "color:green;" > GeeksforGeeks </ h1 > < p id = "GFG_UP" ></ p > < button id = "button" onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" ></ p > < script > var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = ["h1", "GFG_UP", "button", "GFG_DOWN"]; up.innerHTML = "Click on the button to check the type of element."; function GFG_Fun() { var id = arr[Math.floor(Math.random() * arr.length)]; down.innerHTML = "The type of element of id = '" + id + "' is " + document.getElementById(id).tagName; } </ script > |
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 using the approach discussed above.
html
< h1 id = "h1" style = "color:green;" > GeeksforGeeks </ h1 > < p id = "GFG_UP" ></ p > < button id = "button" onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" ></ p > < script > var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = ["h1", "GFG_UP", "button", "GFG_DOWN"]; up.innerHTML = "Click on the button to check the type of element."; function GFG_Fun() { var id = arr[Math.floor(Math.random() * arr.length)]; down.innerHTML = "The type of element of id = '" + id + "' is " + document.getElementById(id).nodeName; } </ script > |
Output:

How to get the type of DOM element using JavaScript?
Please Login to comment...