Bada
Bada's Coding

Bada's Coding

(TypeScript) How to Handle addEventListener

Bada's photo
Bada
·Aug 12, 2022·

1 min read

Below is the example.

const $button = document.querySelector('button');

// optional chaining
// The button should exist.
$button?.addEventListener('click', (e) => {
  // The target should exist.
  if (e.target) {
    // For innerText, the target should be HTMLElement.
    if (e.target instanceof HTMLElement) {
      alert(e.target.innerText);
    }
  }
});
 
Share this