Skip to content Skip to sidebar Skip to footer

How Can You Detect Which Element In A Class Was Clicked On With Javascript?

Let's say we have a unordered list with a class:

Solution 1:

Solution 2:

Solution 3:

Add a click handler to the ul, something like:

$('.list-class').on(
  'click',
   function(e){
     e = e || event;
     varfrom = e.target || e.srcElement;
     if (/^a$/i.test(from.tagName)){
        alert('you clicked '+from.innerHTML);
     }
   });

See this jsFiddle

Solution 4:

Do a Jquery Trick as

$("#list-class li").click(function() {
    alert($(this).prevAll().length+1);
});

Here is the FIDDLE

Solution 5:

EDIT:event.targetreturns DOM element that initiated the event.

$('.list-class').click(function(e){  
   alert(e.target.nodeName);
});

Check this in JSFiddle

Post a Comment for "How Can You Detect Which Element In A Class Was Clicked On With Javascript?"