0

I have code that looks like this:

<a href="someline">
<img src="img.jpg"/>
</a>

I have code all over my page, to get the links, and get their href like this:

e.target.href

The problem is, when clicking the link that contains the image, then e.target is the image itself not the anchor tag. I tried setting the href on the image as a bad solution, but e.target.href is undefined on the image.

How do I solve it so that e.target will reference the <a> not the image.

Jacky
  • 393
  • 1
  • 3
  • 13

2 Answers2

3

We really need to see more code, but if the handler is attached to the a elements, use e.currentTarget (or this) rather than e.target.


If not (e.g., you're using event delegation or something), then just check the tagName and use parentNode until you find the a:

var el = e.target;
while (el && el.tagName !== "A") {
    el = el.parentNode;
}
if (el) {
    console.log(el.href);
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

You can attach the onclick event to the image and use Node.parentElement to get the a parent element as you have in your code:

document.getElementById('myImage').onclick = function(e) {
  e.preventDefault();
  
  console.log(e.target.parentElement.href);
};
<a href="someline">
  <img id="myImage" src="https://placehold.it/350x150"/>
</a>
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46