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.
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.
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.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With