How to Get the ID of a Clicked Button or Element in JavaScript

How to Get the ID of a Clicked Button or Element 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. method
  2. method, and

Let's check each method with an example.

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

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

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

Get clicked Button Id using 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 in the function.

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

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

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

function clickedBtn(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 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 refers to the object on which the event originally occurred.

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

For example:

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

In main.js

function clickedBtn() {

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


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