4

When I create a click event listener on a button, if the SVG is clicked inside the button, the event target is <use xlink:href="#star-filled"></use> instead of the element that was registered to the click event.

How do I prevent it from capturing the child as the target element?

HTML

<button type="button" class="rp-form-rating-btn">
  <svg class="rp-star-icon rp-star-four" data-rating="4">
    <use xlink:href="#star-filled"></use>
  </svg>
</button>

JavaScript

var stars = document.querySelectorAll('.rp-form-rating-btn');

for (var i = 0; i < stars.length; i++) {
   stars[i].addEventListener('click', event => {
     console.log(event.target);
   }, false);
}
Always Helping
  • 14,316
  • 4
  • 13
  • 29
Asa Carter
  • 2,207
  • 5
  • 32
  • 62

1 Answers1

4

Use currentTarget instead of a target to capture button instead to svg

currentTarget will allow you to get the element you clicked on!

From MDN: currentTarget always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.

Live Demo:

var stars = document.querySelectorAll('.rp-form-rating-btn');

stars.forEach(function(stars) {
  stars.addEventListener('click', function(event) {
    console.log(event.currentTarget);
  }, false);
})
<button type="button" class="rp-form-rating-btn">
  <svg class="rp-star-icon rp-star-four" data-rating="4">
    <use xlink:href="#star-filled"></use>
  </svg>
</button>
Always Helping
  • 14,316
  • 4
  • 13
  • 29