I have three buttons with images and I'm trying to get the ID of the clicked one, but when i click in the button (with an image) it just return the ID of the image, not the button (sometimes return the ID of the button too). There's something that im missing? Or another way to do that? please, help!
Here is my code:
buttons = document.querySelectorAll('button');
buttons.forEach((btn) => btn.addEventListener("click", (e) => {
let userChoice = e.target.id;
console.log(userChoice);
}));
<button id="myBtn1"><img src="images/img1.png"></button>
<button id="myBtn2"><img src="images/img2.png"></button>
<button id="myBtn3"><img src="images/img3.png"></button>
If you want to test, just run the code and click in the buttons. (sorry if i'm not clear, i'm new here).
Please replace:
e.target.id with e.currentTarget.id
current target always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.