Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the class of the element that fired an event using JQuery

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

like image 653
Redbox Avatar asked Jun 14 '12 02:06

Redbox


People also ask

How do you get the class of event target?

To check if event. target has specific class, call the classList. contains() method on the target object, e.g. event. target.

How do you get the element that triggered an 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 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.

How can you select an element class using jQuery?

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.


1 Answers

Try:

$(document).ready(function() {     $("a").click(function(event) {        alert(event.target.id+" and "+$(event.target).attr('class'));     }); }); 
like image 65
broesch Avatar answered Oct 05 '22 16:10

broesch