I use the following attribute on a page to return the inner element clicked in a certain div.
onclick="alert(event.target.innerHTML)";
It properly returns the name if I click on a heading element, but it returns nothing if clicked on an image element.
How can I return the alt name of the image clicked?
2
Answers
Rather than using
innerHTML
, you simply want to get thealt
property instead when using this code on images. Obviously if they don’t have an alt attribute set this’ll return undefined, so you can’t use this on headers etc.onclick="alert(event.target.alt)"
should work for you(also I noticed you had a trailing semicolon in your code snippet, you need to remove that)
Well as @Rory McCrossan mentioned in their comment that it is hard to guess the actual code flow/scenario without your HTML structure, so I have created a minimal re-production of the scenario which I understood from your post. I assume you want to get
innerHTML
for all the other elements, but forimg
you want thealt
attribute. So here is a refactored function for that to check the target element and thenalert
accordingly.I provided "image" as an alt to my
img
element