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

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

The event.target property is designed to get the ID of the element that fired an event in jQuery:

<!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.5.0.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);
            });
        });
    </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):

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

The target property is a reference to the object that dispatched the event. It is often useful to compare event.target to this to determine if the event is being handled due to event bubbling. This keyword refers to an object which is executing the current bit of JavaScript code.