skip to Main Content

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?

Heading element:
enter image description here

Image element:
enter image description here

2

Answers


  1. Rather than using innerHTML, you simply want to get the alt 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)

    Login or Signup to reply.
  2. 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 for img you want the alt attribute. So here is a refactored function for that to check the target element and then alert accordingly.

    I provided "image" as an alt to my img element

    function onElementClick(e) {
      const elem = event.target;
      const message = elem.nodeName.toLowerCase() === 'img' ? elem.alt : elem.innerHTML;
      window.alert(message);
    }
    div:hover,
    img:hover {
      cursor: pointer;
    }
    <html>
    
    <body>
        <div onclick="onElementClick(this)">Some Element</div>
        <div>
            <h1 onclick="onElementClick(this)">Some Heading</h1>
        </div>
        <div>
            <img src="https://plus.unsplash.com/premium_photo-1687892170417-f9a11a402ef7?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8OXx8Y29tcHV0ZXJ8ZW58MHx8MHx8fDA%3D"
                alt="image" width="200" height="auto" onclick="onElementClick(this)" />
        </div>
    </body>
    
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search