Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • jQuery Tutorial
  • jQuery Selectors
  • jQuery Events
  • jQuery Effects
  • jQuery Traversing
  • jQuery HTML & CSS
  • jQuery AJAX
  • jQuery Properties
  • jQuery Examples
  • jQuery Interview Questions
  • jQuery Plugins
  • jQuery Cheat Sheet
  • jQuery UI
  • jQuery Mobile
  • jQWidgets
  • Easy UI
  • Web Technology
Open In App
Next Article:
How to send row data when clicking button using JavaScript ?
Next article icon

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

Last Updated : 22 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To get the ID of a clicked button using JavaScript/jQuery means identifying which specific button was clicked within a webpage. This is useful when multiple buttons exist, and you need to distinguish between them based on their unique ID for further processing.

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

Approach 1: Using JavaScript onClick event

The JavaScript onClick event approach involves adding the onclick attribute to each button. When clicked, the button’s ID is passed to a function, enabling you to identify the clicked button and perform specific actions.

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 onClick event in JavaScript     </title> </head>  <body style="text-align:center;">      <h1 style="color:green;">         GeeksForGeeks     </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>         let el_up = document.getElementById("GFG_UP");         let 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:

Using JavaScript onClick event

Approach 2: Using jQuery on() Method

The jQuery on() method dynamically attaches click events to elements. It captures the button’s ID using $(this).attr("id") when clicked. This approach is flexible, handling both static and dynamically generated buttons efficiently within the DOM.

Syntax: 

$(selector).on(event, childSelector, data, function, map);

Example: This example sets an onClick event by using the on() method for each button, When the button is clicked, the ID of the button is passed to the function, and then print the ID on the screen. 

html
<!DOCTYPE HTML> <html>  <head>     <title>         Get the ID of the clicked button         using jQuery     </title>      <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">     </script> </head>  <body style="text-align:center;">      <h1 style="color:green;">         GeeksForGeeks     </h1>      <p id="GFG_UP" style="font-size: 15px;                            font-weight: bold;">     </p>      <button id="1"> Button1</button>     <button id="2"> Button2</button>     <button id="3"> Button3</button>      <p id="GFG_DOWN" style="color:green;                              font-size: 20px;                              font-weight: bold;">     </p>      <script>         $('#GFG_UP').text("Click on button to get ID");          $("button").on('click', function () {             let t = (this.id);             $('#GFG_DOWN').text("ID = " + t);         });                         </script> </body>  </html> 

Output:

Using jQuery on() Method

Approach 3: Using jQuery click() Method

This method triggers the click event, or adds a function to run when a click event occurs. Click event occurs when an element is clicked. 

Syntax: 

  • Trigger the click event for the selected elements: 
$(selector).click();
  • Adds a function to the click event: 
$(selector).click(function);

Example: This example sets an onClick event by using the click() method for each button, When the button is clicked, the ID of the button is passed to the function, and then print the ID on the screen. 

html
<!DOCTYPE HTML> <html>  <head>     <title>         Get the ID of the clicked button         using jQuery     </title>      <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">     </script> </head>  <body style="text-align:center;">      <h1 style="color:green;">         GeeksForGeeks     </h1>      <p id="GFG_UP" style="font-size: 15px;                            font-weight: bold;">     </p>      <button id="1"> Button1</button>     <button id="2"> Button2</button>     <button id="3"> Button3</button>      <p id="GFG_DOWN" style="color:green;                              font-size: 20px;                              font-weight: bold;">     </p>      <script>         $('#GFG_UP').text("Click on button to get ID");          $("button").click(function () {             let t = $(this).attr('id');             $('#GFG_DOWN').text("ID = " + t);         });                         </script> </body>  </html> 

Output:

Using jQuery click() Method

jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous for it's philosophy of “Write less, do more". You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.


Next Article
How to send row data when clicking button using JavaScript ?

P

PranchalKatiyar
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JQuery
  • Web technologies
  • javaScript
  • JavaScript-Questions
  • jQuery-Questions
  • jQuery

Similar Reads

  • How to count the number of times a button is clicked using JavaScript ?
    At times, it becomes necessary to monitor the number of times a user clicks a button. In this article, we are going to learn how to count the number of times a button is clicked using JavaScript Below are the approaches to count the number of times a button is clicked using JavaScript Table of Conte
    3 min read
  • How to Change the ID of Element using JavaScript?
    We are given an element and the task is to change the ID of elements using JavaScript. ID is unique for any element and it can be assigned to an element only once. JavaScript provides a method to access this id and also to manipulate the id. Syntax:Selected_element.id = newID;Below are the appraoche
    3 min read
  • How to Change the Button Label when Clicked using JavaScript ?
    Changing the Label of the Button element when clicked in JavaScript can be used to provide more information to the user such as the text of the Submit button will change to the Submitted as soon as the form submission is completed. The below approaches can be used to accomplish this task: Table of C
    2 min read
  • How to send row data when clicking button using JavaScript ?
    Sending row data when clicking a button using JavaScript refers to capturing data from a specific table row (or similar structure) when a button within that row is clicked. This data can then be processed or sent to a server for further actions, like form submission. Approach:HTML Table Structure: E
    2 min read
  • How to get the outer html of an element using jQuery ?
    Sometimes, there is a need to get the entire HTML element by its id and not merely its contents, for doing so, we shall use the HTML DOM outerHTML Property to get the outer HTML of HTML element. Syntax: document.getElementById("your-element-id").outerHTML) You can use a variable and initialize it to
    2 min read
  • How to get the type of DOM element using JavaScript ?
    The task is to get the type of DOM element by having its object reference. Here we are going to use JavaScript to solve the problem. Approach 1: First take the reference of the DOM object to a variable(Here, In this example an array is made of IDs of the element, then select random ID and select tha
    2 min read
  • How to hide/show an image on button click using jQuery ?
    In this article, we will see how we can hide or show any particular image in jQuery when a button gets clicked. This is quite easy to do with some lines of jQuery code. Before we jump to the topic, let's know which methods of jQuery will be used for this. So there is a method called show() and anoth
    3 min read
  • How to get form data using JavaScript/jQuery?
    The serializeArray() method creates an array of objects (name and value) by serializing form values. This method can be used to get the form data. Syntax: $(selector).serializeArray() Parameter: It does not accept any parameter. Return Value: It returns all the value that is inside the inputs fields
    1 min read
  • How to get the class of a element which has fired an event using JavaScript/JQuery?
    One can use JavaScript and JQuery to retrieve the class of an element that triggers an event. By capturing the event and accessing the class attribute, developers can dynamically identify the specific element involved in the interaction. Below are the methods to get the class of an element that has
    3 min read
  • How to Get the Value of an Input Text Box using jQuery?
    When working with forms or interactive web pages, sometimes need to get the values entered into the input fields. This article provide a complete guide on how to get the value o an input text box using jQuery. Below are the different approaches to get the value of an input text box using jQuery: Get
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences