W3docs

How to Get the ID of the Element that Fired an Event in jQuery

This tutorial provides you the method of getting the id of the element fired an event in jQuery. Read about the event.target property and this keyword.

There is a simple method that is used to get the ID of the element that fires an event.

The <kbd class="highlighted">event.target</kbd> property returns the element that fired the event. You can access its ID using the .id property:

Javascript (Jquery) event target get Id

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <style>
      div,p,span {
        padding: 30px;
        display: block;
        border: 3px solid green;
      }
    </style>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <div id="divId">
      <p id="pId">
        <span id="spanId">Click anywhere.</span>
      </p>
    </div>
    <script>
      $(document).ready(function() {
          $(document).click(function(event) {
              alert("Clicked: " + event.target.nodeName + ", id: " + (event.target.id || "none"));
            });
        });
    </script>
  </body>
</html>

The “this” keyword will also work, however, it is not a jQuery object, so to use a jQuery function on it, you must refer to it as $(this):

Javascript (Jquery) this keyword

$(document).ready(function () {
  $("a").click(function (event) {
    // this.append will not work
    $(this).append("Click");
  });
});

The <kbd class="highlighted">event.target</kbd> property is a reference to the object that dispatched the event. It is often useful to compare <kbd class="highlighted">event.target</kbd> to <kbd class="highlighted">this</kbd> to determine if the event is being handled due to event bubbling. The <kbd class="highlighted">this</kbd> keyword refers to the object executing the current JavaScript code.