is there anyway to get the class when click event is fired. My code as below, it only work for id but not class.
$(document).ready(function() { $("a").click(function(event) { alert(event.target.id + " and " + event.target.class); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <body> <a href="#" id="kana1" class="konbo">click me 1</a> <a href="#" id="kana2" class="kinta">click me 2</a> </body> </html>
jsfiddle code here
To check if event. target has specific class, call the classList. contains() method on the target object, e.g. event. target.
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.
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.
In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.
Try:
$(document).ready(function() { $("a").click(function(event) { alert(event.target.id+" and "+$(event.target).attr('class')); }); });
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