0

I have a nested elements:

<a href="www.google.com">
  <b>Bold test</b>
  <i> Italics </i>
  <span>hello</span>
</a>

however the above is dynamically generated content and hence there can be no guarantee that this structure will remain the same. For example: I can also have a structure like:

<a href="www.google.com">
  <span>hello</span>
</a>

or simply:

<a href="www.google.com">click me</a>

in all cases I'm trying to get to the tag using the href attribute:

onclick(eve) {
  if (eve.target.href || eve.target.parentNode.href || eve.target.parentNode.parentNode.href) {
    //do something
  }
}

basically I do not want to keep checking for parentNode to get to the href attribute of tag. is there a way to get to no matter how deeply nested that element is from the target?

user1234
  • 3,000
  • 4
  • 50
  • 102

1 Answers1

2

You can navigate to the nearest ancestor that matches a particular selector string with .closest:

someElement.addEventListener('click', (e) => {
  const a = e.target.closest('a');
  if (a) {
    // do something with a.href
  }
});

This will work even if the someElement is the <a> itself.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320