R
R
Ross Alex2021-11-20 10:56:41
JavaScript
Ross Alex, 2021-11-20 10:56:41

How to correctly set and handle the Click event?

Good afternoon, colleagues!

There are links/buttons (just an example) that have data in their attributes:

<button data-link data-amount="10"><span>10</span></button>
<a href="" data-link data-amount="20"><span>20</span></a>

There is an event handler:
document.querySelectorAll('[data-link]').forEach(el => el.addEventListener('click', function(e) {
  console.log(e.target);
  e.preventDefault();
}));

Problem : if the click does not follow the text of the link, the A / BUTTON itself is shown in the console, on which the handler was placed. But if the click is on the text in the span, then e.target will be SPAN. How to do it right so that you can read the attributes of exactly A / BUTTON?

Thanks for the help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GrayHorse, 2021-11-20
@Wacdis

currentTarget

Always matches the element on which the event handler was assigned, as opposed to the Event.target, which identifies the element on which the event originated.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question