How to Get the Tag Name of a DOM Element in JavaScript

08/02/2021

Contents

In this article, you will learn how to get the tag name of a DOM element in JavaScript.

Getting the tag name of a DOM element in JavaScript

In JavaScript, you can get the tag name of a DOM element using the tagName property. This property returns a string containing the tag name of the element in uppercase letters.

Example
const element = document.getElementById('myElement');
const tagName = element.tagName;
console.log(tagName); // Output: the tag name of the element in uppercase letters

Note that the tagName property returns the same string value for all elements of the same tag name, regardless of their attributes or content. For example, both <div> elements with different id attributes have the same tag name of DIV.

To get the tag name of an element in lowercase letters, you can use the nodeName property instead.

Example
const element = document.getElementById('myElement');
const tagName = element.nodeName.toLowerCase();
console.log(tagName); // Output: the tag name of the element in lowercase letters

This example first gets the tag name using the nodeName property, and then converts it to lowercase using the toLowerCase() method.

It’s worth noting that the tagName and nodeName properties are only applicable to element nodes. If you try to access these properties on a non-element node (such as a text node or comment node), you will get unexpected results.