Since I do not have enough credits to comment, adding a new answer.
Unlike the answer shared by @CubeInTheBox, I think leveraging the concept of event capturing/bubbling for the respective element makes for a better implementation rather than adding an event listener to each of the target elements.
For the example shared above, the alternative would be:
<ul>
<li class="list_item" data-mydata="hello there!">
<img src="..." alt="" width="50", height="50">
</li>
<li class="list_item" data-mydata="hello world">
<img src="..." alt="" width="50", height="50">
</li>
</ul>
<script>
const parentElement = document.querySelector('ul');
parentElement.addEventListener('click', e => {
// If you want to add the listener on li alone and not on image
if (e.target.className === 'list_item') {
const myvalue = e.target.dataset.mydata;
console.log(myvalue);
}
});
</script>
NOTE that e.currentTarget
wouldn’t work for this case, as it would return the parent ul
to which the event is bound.