Getting the id of the element that fired an event using jQuery

Learn, how can we get the ID of the element which fired an event using jQuery?
Submitted by Pratishtha Saxena, on August 23, 2022

An event is something that is triggered and performs a particular task on some operation performed. Like on clicking the button, the user sees a new section of data. This is an event. It is linked to an element that when clicked or operated triggers the event attached to it.

To know which event is fired on clicking something is necessary if some other task is related or dependent on this. For this, we need to know the id or name of the element that fired a particular event.

In jQuery, this can be done using the event .target property. Using this we can get the ID of the element and also the name of it which fired the event.

Syntax to get the id of the element that fired an event

console.log(event.target.id);
console.log(event.target.node);

.id will return the ID whereas, .node will return the node, i.e., the name of the element. The above statement over here will print the ID or name of the element which fired the event.

This can be easily understood by the example given below.

Example to get the id of the element that fired an event using jQuery

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2 id="myHeading">When this is clicked, you'll get its id.</h2>
    <p id="myPara">When this is clicked, you'll get its id.</p>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function() {
    	$(document).click(function(event) {
    		console.log(event.target.id);
    	})
    })       
  </script>
</html>

Output:

Example: Getting the id of the element that fired an event





All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.