Home > Back-end >  How to trigger the parent element when firing an event?
How to trigger the parent element when firing an event?

Time:10-08

I want to console log the button every time the button is clicked but if I click any child element within the button, the child gets printed instead which is not I want. How do I make sure the element which has the event listener is printed?

 const onCrossClick = (e) => {
   console.log(e.target);
 };
<button
  className="delete-button"
  onClick={onCrossClick}
>
  <i className="fas fa-times-circle fa-2x"></i>
</button>

CodePudding user response:

const onCrossClick = (e) => {
   console.log(e.currentTarget);
};

<button
  className="delete-button"
  onClick={onCrossClick}>    
     <i className="fas fa-times-circle fa-2x"></i>
</button>

CodePudding user response:

Use closest().

const onCrossClick = (e) => {
   console.log(e.target.closest("button"));
};
  • Related