Trying to get the id of the element, like an elementary procedure, but does not find anything (undefined). Code:

function reserve() { alert(this.id); }; 
 <a id="qweqwe" onclick="reserve();" href="#openModal2">тратата</a> 

So the same does not work:

 alert($(this).attr('id')); 

jQuery connected

 <script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
  • alert($('#qweqwe')); what returns? - Kernel Panic
  • [object Object] - Alexander Bychenko
  • why you decided that function reserve() { alert(this.id); }; function reserve() { alert(this.id); }; Should the item id be displayed? - Alexey Shimansky
  • the parent thus gets alert ($ (this) .parent ()); id should not? - Alexander Bychenko
  • let's start from the beginning, do you know what this in the context of a function?) Why did you decide that it points to an element? - Alexey Shimansky

1 answer 1

In your example:

 function reserve() { alert(this.id); }; 

this will be the window object. To get the current item on which you clicked, you need to event onclick="reserve(**this**);" pass this .

And then:

 function reserve(element) { alert(element.id); }; 

Will return your ID.

Full sample code:

 function reserve(element) { alert(element.id); }; 
 <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <a id="qweqwe" onclick="reserve(this);" href="#openModal2">тратата</a> 

  • Yes, thanks, it works that way) And how can I get the id of the parent of this link in this case? - Alexander Bychenko
  • you can go upstairs, element.parentNode.id - Vasily Barbashev