Explain Codes LogoExplain Codes Logo

How can I determine the type of an HTML element in JavaScript?

javascript
dom-manipulation
javascript-utility-functions
html-element-inspection
Nikita BarsukovbyNikita Barsukov·Feb 9, 2025
TLDR

To rapidly identify an HTML element's type, you can use the element.tagName property, which returns the name in uppercase of the HTML tag:

console.log(document.getElementById('myElement').tagName); // outputs 'DIV' for: <div id="myElement"></div>

The beauty of tagName lies in its reliability and universal applicability to any HTML element, returning a capitalized, straightforward tag identifier.

Beyond the basic: a deeper dive into HTML elements

While tagName is undeniably effective for a quick scan of your HTML element's type, real-world scenarios often demand a more nuanced approach.

Utilizing nodeName for broader node type identification

When you need to consider more than just HTML node types, consider using the nodeName property:

console.log(document.getElementById('myElement').nodeName); // On a side note, it's not related to your cat named Node!

This property shares similarities with tagName but applies to all nodes, not just elements. For XML documents, bear in mind that nodeName is case-sensitive.

A closer look on particular interfaces with instanceof

To ensure your element is acting in the right movie, doubting the performance of a particular role, check it with the instanceof operator:

const myInput = document.querySelector('input[type=text]'); console.log(myInput instanceof HTMLInputElement); // true, 'cause it's text input and not a wild input type trying to be the next Johnny Depp.

Differentiating between HTML elements is a breeze with instanceof.

Real world scenarios

Recognizing an element's type is crucial for DOM manipulation. Dynamic rendering or optimizing form behavior are typical examples.

Practical examples

  • Menu settings: Render different controls for <div>, <span>, or <input>.
  • Form validation: Different validation logic for HTMLInputElement or HTMLSelectElement.
  • Custom styling: Apply styles for <button> or HTMLButtonElement.

Avoid common pitfalls

  • SVG or MathML namespaces differ from HTML in nodeName.
  • For HTML documents, tagName and nodeName are always uppercase.
  • instanceof can't swim across different windows or frames, check ownerDocument instead.

Prowess in HTML element inspection

Leveraging element properties

  • element.type: For input elements; specifies type (e.g., "text", "checkbox").
  • element.id and element.className: Useful selectors that can suggest element type.

Exploiting custom data attributes

Use element.dataset to assign and retrieve specific types, thereby increasing readability and maintainability.

Emulating utility functions

Compact utility functions as in jQuery abstract these checks. For instance:

$('selector').is(':input') // Checks if the selector is an input element. Works faster than a cat catching a laser pointer!