get tagName by click on elments

How to Get tagName by Clicking on Elements?

If you want to get the name of the tag of an HTML element by clicking on it, you can use JavaScript to achieve this. The tagName property returns the name of the tag of an element. Here are two ways to get the tagName:

Method 1: Using onclick Event Handler

You can use the onclick event handler to get the tagName of an element when it is clicked. Here is an example:


<div id="myDiv" onclick="getTagName()">
    <p>Click Me</p>
</div>

<script>
function getTagName() {
    var element = document.getElementById("myDiv");
    var tagName = element.tagName;
    alert(tagName);
}
</script>

In this example, we have a div element with an id of "myDiv" and a paragraph element inside it. When the div is clicked, the getTagName() function is called. The function gets the element by its id and then gets the tagName property of the element. The tagName is then alerted.

Method 2: Using addEventListener()

You can also use the addEventListener() method to add a click event listener to an element and get the tagName when it is clicked. Here is an example:


<div id="myDiv">
    <p>Click Me</p>
</div>

<script>
var element = document.getElementById("myDiv");
element.addEventListener("click", getTagName);

function getTagName() {
    var tagName = this.tagName;
    alert(tagName);
}
</script>

In this example, we have a div element with an id of "myDiv" and a paragraph element inside it. We get the element by its id and add a click event listener to it using the addEventListener() method. When the element is clicked, the getTagName() function is called. The function gets the tagName property of the element using the this keyword, which refers to the element that was clicked. The tagName is then alerted.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe