Problem
Is it possible to obtain the ID of the element that triggers an event?
Something along these lines comes to mind:
Except that if the event is triggered from the first form, the var test should have the id “aaa,” and if the event is fired from the second form, the var test should include the id “bbb.”
Asked by Joda
Solution #1
The element that generated the event is always referred to as event.target in jQuery, where event is the parameter supplied to the method. http://api.jquery.com/category/events/event-object/
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});
This will also work, but it is not a jQuery object, so you must refer to it as $(this) if you want to use a jQuery function on it, for example:
$(document).ready(function() {
$("a").click(function(event) {
// this.append wouldn't work
$(this).append(" Clicked");
});
});
Answered by samjudson
Solution #2
Try this as an example! It’s effective!
jQuery("classNameofDiv").click(function() {
var contentPanelId = jQuery(this).attr("id");
alert(contentPanelId);
});
Answered by Gemma
Solution #3
Despite the fact that it has been discussed in prior postings, I wanted to emphasize the following:
$(event.target).id is undefined
$(event.target)[0]. The id attribute is returned by id.
The id attribute is also provided by event.target.id.
The id attribute is returned by this.id.
and
$(this).id is undefined.
The distinction is between jQuery objects and DOM objects, of course. Because “id” is a DOM property, it must be used on a DOM element object.
(It threw me off, therefore it threw someone else off, too.)
Answered by dsch
Solution #4
You can use jQuery for any event, not just jQuery.
var target = event.target || event.srcElement;
var id = target.id
For IE, if event.target fails, event.srcElement is used instead. To be clear, the code above does not require jQuery, but it does work with it.
Answered by Ally
Solution #5
You can refer to the object that called the function using (this).
When you’re inside a callback function (in the context of jQuery), such as the click, each, bind, and other methods, ‘this’ is a DOM element.
Here’s where you can find out more information: http://remysharp.com/2007/04/12/jquerys-this-demystified/
Answered by Espo
Post is based on https://stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event