Is there any way to get the ID of the element that fires an event?
I'm thinking something like:
<html>
<head>
<script type="text/javascript" src="starterkit/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a").click(function () {
var test = caller.id;
alert(test.val());
});
});
</script>
</head>
<body>
<form class="item" id="aaa">
<input class="title"></input>
</form>
<form class="item" id="bbb">
<input class="title"></input>
</form>
</body>
</html>
Except of course that the var test
should contain the id "aaa"
, if the event is fired from the first form, and "bbb"
, if the event is fired from the second form.
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/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.:this.element.attr("id")
works fine in IE8.I generate a table dynamically out a database, receive the data in JSON and put it into a table. Every table row got a unique
ID
, which is needed for further actions, so, if the DOM is altered you need a different approach:Element which fired event we have in event property
We get DOM node object on which was set event handler.
Most nested node which started bubbling process we have in
Event object is always first attribute of event handler, example:
More about event delegation You can read in http://maciejsikora.com/standard-events-vs-event-delegation/
In the case of delegated event handlers, where you might have something like this:
and your JS code like so:
You'll more than likely find that itemId is
undefined
, as the content of the LI is wrapped in a<span>
, which means the<span>
will probably be the event target. You can get around this with a small check, like so:Or, if you prefer to maximize readability (and also avoid unnecessary repetition of jQuery wrapping calls):
When using event delegation, the
.is()
method is invaluable for verifying that your event target (among other things) is actually what you need it to be. Use.closest(selector)
to search up the DOM tree, and use.find(selector)
(generally coupled with.first()
, as in.find(selector).first()
) to search down it. You don't need to use.first()
when using.closest()
, as it only returns the first matching ancestor element, while.find()
returns all matching descendants.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)