Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect current element id in jQuery?

Tags:

I have some HTML codes:

<input type="button" id="btn1" class="myButton" value="Button 1"/> <input type="button" id="btn2" class="myButton" value="Button 2"/> 

I need to run a jQuery function whenever user click each button, and I have to do it using their class.

$('.myButton').click(function() {    // do something }); 

But what I should to do, depends on the current element Id.

My question is that how can I detect which element called this function? I need to know its id.

like image 251
Mohammad Saberi Avatar asked Dec 28 '11 10:12

Mohammad Saberi


People also ask

How do you know if an element has an ID?

Use the querySelector() method to check if an element has a child with a specific id, e.g. if (box. querySelector('#child-3') !== null) {} . The querySelector method returns the first element that matches the provided selector or null of no element matches.

Why this is used in jQuery?

The this Keyword is a reference to DOM elements of invocation. We can call all DOM methods on it. $() is a jQuery constructor and in $(this), we are just passing this as a parameter so that we can use the jQuery function and methods.


1 Answers

You can use this to access current element and then this.id will give you the id of the current element.

$('.myButton').click(function() {     alert(this.id); }); 
like image 183
Emre Erkan Avatar answered Oct 20 '22 14:10

Emre Erkan