First of all I do not want to use jQuery, just pure javascript; please don\'t link to duplicate jQuery posts.
If I have a list like
You can use this:
var link = document.getElementById("bulk");
attachEvent(link, "click", EventHandler);
function attachEvent(element, type, handler) {
if (element.addEventListener) element.addEventListener(type, handler, false);
else element.attachEvent("on"+type, handler);
}
function EventHandler(e) {
console.log(e.target.id);
}
fiddle
This work if li
has children` elements:
fiddle example with children
You could add an event listener to the parent ul
and then use e.target.id
to get the id
of the clicked element. Just check to make sure that the clicked element is actually an li
since it's possible you may not be clicking on one.
Example Here
var ul = document.getElementById('bulk'); // Parent
ul.addEventListener('click', function(e) {
if (e.target.tagName === 'LI'){
alert(e.target.id); // Check if the element is a LI
}
});
As pointed out in the comments, this approach won't work when the child of an li
is clicked. To solve this, you would need to check to see if the parent element of the clicked element is the one that the click event is attached to.
Example Here
var ul = document.getElementById('bulk'); // Parent
ul.addEventListener('click', function (e) {
var target = e.target; // Clicked element
while (target && target.parentNode !== ul) {
target = target.parentNode; // If the clicked element isn't a direct child
if(!target) { return; } // If element doesn't exist
}
if (target.tagName === 'LI'){
alert(target.id); // Check if the element is a LI
}
});
pass its id as parameter into the onclick-function.
this.getAttribute('id')