JavaScript theorytheory 0/50 · 0%
Browser · medium

42. The DOM and events

Selecting, updating and delegating.

Select with `querySelector`, update with `textContent` (safe) rather than `innerHTML` (an XSS risk with untrusted data). Event delegation attaches one listener to a parent and inspects `event.target`.

list.addEventListener("click", (e) => {
  const btn = e.target.closest("button[data-id]");
  if (btn) select(btn.dataset.id);
});

Remove listeners you add to `window` or `document` when a component unmounts.

Check your understanding

  1. 1. Which is safe with untrusted text?

  2. 2. What is event delegation?

  3. 3. What leaks if you forget cleanup?