1

If I have a bunch of buttons in HTML and run:

const buttons = document.querySelectorAll('button');

buttons.forEach((btn) => {
  btn.addEventListener('click', (e) => {
    console.log(btn.textContent);
    console.log(e.target.textContent);
  });
});

What is the difference between btn and e.target? I know I could use event delegation to make this cleaner but, want to know if these are the exact same and can be used interchangeably.

QThelp
  • 31
  • 3
  • 2
    Both are just references to the same object. There is no difference other than the way you're refering them. But, you only have access to the `btn` variable inside the loop. `event.target` is available regardless of the scope of the event handler callback. – Emiel Zuurbier Apr 09 '22 at 21:36
  • Does this answer your question? [What is DOM Event delegation?](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) – Yogi Apr 10 '22 at 07:55

0 Answers0