Get the type of DOM element using JavaScript

Don’t know how to figure out the type of an element when dealing with JavaScript and DOM (Document Object Model)? Here is the answer. The element type can be useful for the implementation of special styles, event handling, or DOM manipulation.
In this article, we will discuss several techniques that can be used to get to the type of a DOM element using JavaScript, with code examples for each step.
1. Using tagName
With the tagName attribute, you can make a request to a server that returns a string named after the tag of the input element that the user has clicked.

Example:

Example:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get DOM Element Type</title>
</head>
<body>
    <div id="myDiv">This is a div</div>
    <button id="myButton">Click Me</button>
    <script>
        let divElement = document.getElementById("myDiv");
        let buttonElement = document.getElementById("myButton");
        console.log(divElement.tagName); // Output: DIV
        console.log(buttonElement.tagName); // Output: BUTTON
    </script>
</body>
</html>

 


2.
Using nodeName
Just like the tagName property, nodeName also provides the name of the element in uppercase. It can work on any type of node such as text and comment node.
Example:

<script>
console.log(divElement.nodeName); // Output: DIV
console.log(buttonElement.nodeName); // Output: BUTTON
</script>

3. Using instanceof
To find out the type of an element, use the instanceof operator that tells you if an object is a particular type of HTML element.
Example:

<script>
console.log(divElement instanceof HTMLDivElement); // Output: true
console.log(buttonElement instanceof HTMLButtonElement); // Output: true
console.log(buttonElement instanceof HTMLInputElement); // Output: false
</script>

 

4. Using constructor.name
If you need the exact constructor name of the element, you can use constructor.name.
Example:

<script>
console.log(divElement.constructor.name); // Output: HTMLDivElement
console.log(buttonElement.constructor.name); // Output: HTMLButtonElement
</script>

 

5. Handling Dynamic Elements
If elements are dynamically created, you can still check their types using the above methods.
Example:

<script>
let newElement = document.createElement("span");
console.log(newElement.tagName); // Output: SPAN
</script>

 

Conclusion
Determining the type of a DOM element in JavaScript can be accomplished via:
tagName and nodeName for straightforward tag checking.
instanceof for confirming if at least one instance is of certain class.
constructor.name for detailed constructor name retrieval.

Thus, the different methods can aid in the accomplishment of various objectives, and the choice of one depends on the nature of the requirement. Good coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top