javascript

Get Tag Name of an Element using Javascript

In JavaScript, the tag name of an HTML element can be retrieved using the .tagName property. The .tagName property returns a string representing the tag name of the provided element.

Get the Tag Name of an Element using Javascript

To get the tag name of an HTML element using javascript:

  1. First, get the HTML element for eg. var element = document.getElementById("tag_id");
  2. Use tagName property to get the tag name - element.tagName.

Example 1

Let's assume we have an HTML element with the following markup:

<div id="example">text</div>

We can use the .tagName property to retrieve the tag name of this element, as shown below:

var element = document.getElementById("example");
var tagName = element.tagName;

// tagName = "div"

This code example is retrieving the tag name of an element by its ID. In this example, the element is identified by the ID "example", and the tagName variable will be set to the element's tag name, in this case, "div".


Example 2

Let's assume we have an HTML element with the following markup:

<p class="paragraph">text</p>

We can use the .tagName property to retrieve the tag name of this element, as shown below:

var element = document.querySelector(".paragraph");
var tagName = element.tagName;

// tagName = "p"

Was this helpful?