[Solved-5 Solutions] Getting the ID of the element that fired an event - javascript tutorial



Problem:

How to get the ID of the element that fired an event ?

Solution 1:

  • The target property can be the element that listed for the event or a child of it.
  • It is useful to compare event.target to this in order to determine if the event is being handled due to event bubbling.
  • This property is useful in event delegation, when events bubble.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>event.target demo</title>
  <style>
  span, strong, p {
    padding: 8px;
    display: block;
    border: 1px solid #999;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div id="log"></div>
<div>
  <p>
    <strong><span>click</span></strong>
  </p>
</div>
 
<script>
$( "body" ).click(function( event ) {
  $( "#log" ).html( "clicked: " + event.target.nodeName );
});
</script>
 
</body>
</html>

Solution 2:

In jQuery event.target always refers to the element that triggered the event, where 'event' is the parameter passed to the function.

$(document).ready(function() {
    $("a").click(function(event) {
        alert(event.target.id);
    });
});

Solution 3:

To use a jQuery function, you must refer to it as '$(this)' object.

$(document).ready(function() {
    $("a").click(function(event) {
        // this.append wouldn't work
        $(this).append(" Clicked");
    });
});

Solution 4:

You can use this code:

jQuery("classNameofDiv").click(function() {
    var contentPanelId = jQuery(this).attr("id");
    alert(contentPanelId);
});

Solution 5:

  • $(event.target).id is undefined
  • $(event.target)[0].id gives the id attribute.
  • event.target.id also gives the id attribute.
  • this.id gives the id attribute
  • $(this).id is undefined.

"id" is a DOM function so you have to be on the DOM element object to use it.


Related Searches to Getting the ID of the element that fired an event - javascript tutorial