Javascript get "clicked" element addEventListener
You can use the event
object and access its target
property
document.getElementById("divId").addEventListener("click", someFunction);
function someFunction(event) {
console.log(event.target.id);
}
<div id="divId">
<span id="one">one</span>
<span id="two"> two</span>
</div>
If the user clicked on a node that was a child of the element the user wanted to test e.target
will be a different node. The sensible way to check this nowadays is to listen at the document level and iterate the path (or use some delegation library, of which there are many):
Add one event listener to the document:
const isOnId = (path,id) => path.some(element => element.id === id);
document.addEventListener('click',function(e) {
if(isOnId(e.path,'two')) {
//you clicked on or in element with an id two
} else {
//you clicked on something else
}
});
Adam's answer is correct and saves a lot of headaches. However there's a better and easiest way to acieve this. Please check this answer
Makes use of Event.currentTarget and it goes like this:
<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 items = document.querySelectorAll(".list_item");
items.forEach(node => {
node.addEventListener("click", e => {
let myvalue = e.currentTarget.dataset.mydata;
console.log(myvalue); //hello there! || hello world It depends on which element the user has clicked
})
})
</script>
I hope this is useful