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:

You may try this

functionaddEvent(elem, event, fn)
{
    if (elem.addEventListener)
    {
        elem.addEventListener(event, fn, false);
    }
    else
    {
        elem.attachEvent("on" + event, function() {
            return(fn.call(elem, window.event));   
        });
    }
}

addEvent(window, 'load', function(e){
    var list = document.querySelector('.list-class');
    addEvent(list, 'click',  function(e){
         e = e || window.event;
         var el = e.target || e.srcElement;
         alert(el.innerHTML);
    });
});

DEMO.

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?"