How to get href of anchor when the event.target is HTMLImageElement?

Rather than adding a global click handler, why not just target only anchor tags?

var anchors = document.getElementsByTagName("a");
for (var i = 0, length = anchors.length; i < length; i++) {
  var anchor = anchors[i];
  anchor.addEventListener('click', function() {
    // `this` refers to the anchor tag that's been clicked
    console.log(this.getAttribute('href'));
  }, true);
};

If you want to stick with the document-wide click handler then you could crawl upwards to determine if the thing clicked is-or-is-contained-within a link like so:

document.addEventListener('click', function(event) {
    event = event || window.event;
    var target = event.target || event.srcElement;

    while (target) {
      if (target instanceof HTMLAnchorElement) {
        console.log(target.getAttribute('href'));
        break;
      }

      target = target.parentNode;
    }
}, true);

This way at least you'd avoid writing brittle code that has to account for all of the possible types of anchor-children and nested structure.


Instead of looping all anchors in the DOM, lookup from the event.target element.
Using JavaScript's .closest() MDN Docs

addEventListener('click', function (event) {
  event.preventDefault();                     // Don't navigate!
  const anchor = event.target.closest("a");   // Find closest Anchor (or self)
  if (!anchor) return;                        // Not found. Exit here.
  console.log( anchor.getAttribute('href'));  // Log to test
});
<a href="http://stackoverflow.com/a/29223576/383904">
  <span>
      <img src="//placehold.it/200x60?text=Click+me">  
  </span>
</a>

<a href="http://stackoverflow.com/a/29223576/383904">
  Or click me
</a>

it basically works like jQuery's .closest() which does

Closest or Self (Find closest parent... else - target me!)

better depicted in the example above.