Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the ID of the element that fired an event

Is there any way to get the ID of the element that fires an event?

I'm thinking something like:

$(document).ready(function() {    $("a").click(function() {      var test = caller.id;      alert(test.val());    });  });
<script type="text/javascript" src="starterkit/jquery.js"></script>    <form class="item" id="aaa">    <input class="title"></input>  </form>  <form class="item" id="bbb">    <input class="title"></input>  </form>

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.

like image 272
Joda Avatar asked Sep 07 '08 08:09

Joda


People also ask

How do I find the ID of an element in an event?

You can use event.target.id in event handler to get id of element that fired an event.

Which of the property method can be used to get the element that fired event?

Answer: Use the event. target Property You can use the event. target property to get the ID of the element that fired an event in jQuery. This property always refers to the element that triggered the event.

How do you target a JavaScript ID?

To select an HTML ID using JavaScript we need to point to it and then store it as a variable. Here is the one line of JavaScript we need to target this element and store it as a variable: Code from a text editor: const chocolateDescription = document. getElementById('chocolateCupcake');

How will you obtain the DOM element that initiated the event using jQuery?

target is an inbuilt property in jQuery which is used to find which DOM element will start the event. Parameter: It does not accept any parameter because it is a property not a function. Return Value: It returns which DOM element triggered the event.


1 Answers

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");     }); }); 
like image 52
samjudson Avatar answered Sep 29 '22 23:09

samjudson