How to get the id of a button clicked in JavaScript


In this article, we will learn how to get the id of any button when clicked using vanilla JavaScript.

In JavaScript, we can get the id of any button using the following methods:

  1. this.id method
  2. event.target.id method, and

Let's check each method with an example.

Let's first create the Html Page with three buttons.

 <body>
    <button id="one">Button One</button>
    <button id="two">Button Two</button>
    <button id="three">Button Three</button>
    <script src="main.js"></script>
  </body>

We have added three buttons with ids as one, two, and three.

Get clicked Button Id using this.id in JavaScript.

To pass the button id we have added a click function clickedBtn() on the button in our HTML page.

We will pass the id of the clicked button using this.id in the function.

Here, this refers to the button and its properties like id or values.

<body>
    <button id="one" onclick="clickedBtn(this.id)">Button One</button>
    <button id="two" onclick="clickedBtn(this.id)">Button Two</button>
    <button id="three" onclick="clickedBtn(this.id)">Button Three</button>
    <script src="main.js"></script>
  </body>

And then we will create the function in our main.js file.

function clickedBtn(id) {
  alert(id);
}

The function clickedBtn() does a very simple thing, it takes the passed button id and shows an alert on the browser with the id.

Get the id of a button using event.target.id in JavaScript

We can also get the id of a clicked element using the target event property. Its returns the element that triggered the event.

The event.target refers to the object on which the event originally occurred.

Here, we can get the id of the button from the target property using target.id .

For example:

<body>
    <button id="one" onclick="clickedBtn()">Button One</button>
    <button id="two" onclick="clickedBtn()">Button Two</button>
    <button id="three" onclick="clickedBtn()">Button Three</button>
    <script src="main.js"></script>
  </body>

In main.js

function clickedBtn() {
  alert(event.target.id);
}

Here, as you can see we did not pass any data to the function. The event.target detects the element on which the click occurred and the using target.id we get the button id.

Demo:

how to get the id of a button when clicked in JavaScript


💾 Recommended Articles