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:
You may try this
function addEvent(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);
});
});
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?"