1

I want to call a javascript function when an anchor is clicked and capture the element's href & title attributes. My code works fine if the content of the element is plaintext but when I introduce new elements inside of the anchor tag such as a label & icon then e.target is now the label or icon so I can no longer get the href attribute.

I can write some code that checks the element type and if it's not an anchor find the parent but I'm wondering if there's a better way for my function to get the anchor element from event.target even if a sub element is clicked?

function doStuff(e) {
  console.log(e.target.getAttribute("href"));
  console.log(e.target.getAttribute("title"));
  e.preventDefault();
}
<a href="/bob" title="Bob" onClick="doStuff(event)">
  <i class='fa fa-user'></i>
  <label>Bob</label>
</a>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
ctown4life
  • 835
  • 1
  • 11
  • 24

2 Answers2

3

you could use event.currentTarget, which should give you the anchor element to which you have bound the event

Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25
-2

When a sub/child element is clicked, you can get a reference to the parent through : event.target.offsetParent .

Abe Caymo
  • 193
  • 7