Getting the ID of the element that fired an event
In jQuery event.target
always refers to the element that triggered the event, where event
is the parameter passed to the function. http://api.jquery.com/category/events/event-object/
$(document).ready(function() { $("a").click(function(event) { alert(event.target.id); });});
Note also that this
will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as $(this)
, e.g.:
$(document).ready(function() { $("a").click(function(event) { // this.append wouldn't work $(this).append(" Clicked"); });});
For reference, try this! It works!
jQuery("classNameofDiv").click(function() { var contentPanelId = jQuery(this).attr("id"); alert(contentPanelId);});
Though it is mentioned in other posts, I wanted to spell this out:
$(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.
and
$(this).id
is undefined.
The differences, of course, is between jQuery objects and DOM objects. "id" is a DOM property so you have to be on the DOM element object to use it.
(It tripped me up, so it probably tripped up someone else)