Getting the class of the element that triggered the event using jQuery

exists anyway to get the class when the click event is fired. My code, as shown below, works only for id, but not for class.

HTML:

<html> <body> <a href="#" id="kana1" class="konbo">click me 1</a> <a href="#" id="kana2" class="kinta">click me 2</a> </body> </html> 

JQuery

 $(document).ready(function() { $("a").click(function(event) { alert(event.target.id+" and "+event.target.class); }); }); 

jsfiddle code here

+49
javascript jquery javascript-events
Jun 14 2018-12-12T00:
source share
5 answers

Try:

 $(document).ready(function() { $("a").click(function(event) { alert(event.target.id+" and "+$(event.target).attr('class')); }); }); 
+99
Jun 14 2018-12-12T00:
source share

This will contain the full class (which can be several classes separated by spaces if the element has more than one class). In your code, it will contain either "konbo" or "kinta":

 event.target.className 

You can use jQuery to check classes by name:

 $(event.target).hasClass('konbo'); 

and add or remove them using addClass and removeClass .

+65
Jun 14 2018-12-12T00:
source share

If you are using jQuery 1.7:

 alert($(this).prop("class")); 

or

 alert($(event.target).prop("class")); 
+1
Jun 14 '12 at 3:00
source share
  <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script> </head> <body> <a href="#" id="kana1" class="konbo">click me 1</a> <a href="#" id="kana2" class="kinta">click me 2</a> <script> $(document).ready(function() { $("a").click(function(event) { var myClass = $(this).attr("class"); var myId = $(this).attr('id'); alert(myClass + " " + myId ); }); }) </script>> </body> </html> 

This works for me. There is no event.target.class function in jQuery.

+1
Jun 14 2018-12-12T00:
source share

Caution, since target may not work with all browsers, it works fine with Chrome, but I believe that Firefox (or IE / Edge, I don’t remember) is a little different and uses srcElement. I usually do something like

 var t = ev.srcElement || ev.target; 

that leads to

 $(document).ready(function() { $("a").click(function(ev) { // get target depending on what API in use var t = ev.srcElement || ev.target; alert(t.id+" and "+$(t).attr('class')); }); }); 

Thanks for the nice answers!

0
23 Feb '16 at 19:43
source share



All Articles