Skip to content
the poor coder

get tagName by click on elments

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

<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:

Text

<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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC