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:
- First, get the HTML element for eg. var element = document.getElementById("tag_id");
- 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"
- Get the current month name using javascript
- Get month name from a date using javascript
- Get the day name from given date in Javascript
- Javascript function to get cookie value by name
- Get all child elements of parent element in javascript
- Array.find() - get the very first element satisfy a condition Javascript
- Add a CSS class to element if dark mode is enabled using Javascript