How to useJavaScript onClick event in Javascript

Example: This example sets an onClick event to each button, when the button is clicked, the ID of the button is passed to the function then it prints the ID on the screen. 

html




<!DOCTYPE HTML>
<html>
<head>
    <title>
        Get the ID of the clicked button
        using JavaScript
    </title>
</head>
 
<body style="text-align:center;">
 
    <h1 style="color:green;">
        w3wiki
    </h1>
 
    <p id="GFG_UP" style="font-size: 15px;
                          font-weight: bold;">
    </p>
 
    <button id="1" onClick="GFG_click(this.id)">
        Button1
    </button>
 
    <button id="2" onClick="GFG_click(this.id)">
        Button2
    </button>
 
    <button id="3" onClick="GFG_click(this.id)">
        Button3
    </button>
 
    <p id="GFG_DOWN" style="color:green;
                            font-size: 20px;
                            font-weight: bold;">
    </p>
 
    <script>
        var el_up = document.getElementById("GFG_UP");
        var el_down = document.getElementById("GFG_DOWN");
        el_up.innerHTML = "Click on button to get ID";
 
        function GFG_click(clicked) {
            el_down.innerHTML = "ID = " + clicked;
        }       
    </script>
</body>
</html>


Output:

How to get the ID of the clicked button using JavaScript/jQuery ?

Sometimes a developer has to know the ID of the button that the user has clicked to decide further course of action on a webpage.

So, to get the ID of the clicked button using JavaScript/jQuery we have different approaches which are as follows:

Table of Content

  • Using JavaScript onClick event
  • Using jQuery on() Method
  • Using jQuery click() Method

Similar Reads

Approach 1: Using JavaScript onClick event

Example: This example sets an onClick event to each button, when the button is clicked, the ID of the button is passed to the function then it prints the ID on the screen....

Approach 2: Using jQuery on() Method

...

Approach 3: Using jQuery click() Method

This method adds one or more event handlers for the selected elements and child elements....