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:

How about this if I understand correctly:

var items = document.querySelectorAll('.list-class li');

[].forEach.call(items, function(item){

  var text = item.textContent.trim().toLowerCase();

  item.addEventListener('click', function(){
    if (text == 'all') {
      //...
    }
    //...
  });
});

Solution 2:


Solution 3:

Add a click handler to the ul, something like:

$('.list-class').on(
  'click',
   function(e){
     e = e || event;
     var from = 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.target returns 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?"