In jQuery we sometimes need to find class or Id of element that fires an event in a web page. This simple code below will do the job for getting Class or Id of element that fired an event in jQuery.
First of all we need jQuery so you need to add self hosted jQuery or one from available CDNs. I’m getting it from Google here.
1 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> |
Next is, we have HTML somewhere in web page:
1 2 | <a href="#" id="elem_1" class="first">Anchor 1 is clicked</a> <a href="#" id="elem_2" class="second">Anchor 2 is clicked</a> |
Getting Class or Id of element that fired an event
And the script we need to attend the Id or class:
1 2 3 4 5 6 7 8 9 10 | $(document).ready(function() { $("a").click(function(event) { // Id alert(event.target.id); // Class would be access in bit different manner var xyz = $(event.target).attr('class'); alert(xyz); }); }); |