JavaScript Intermediate DOM & Async · 8 min read

Event Delegation with addEventListener

Lesson 12 of 38 in the JavaScript learning path.

How do I handle clicks on many rows with one listener?

Event delegation puts one listener on a parent instead of one listener on every row. A click anywhere inside the parent bubbles up to that listener. event.target is the node that was hit, which might be a button or a span inside the row. closest walks from that node through its ancestors until it finds a selector such as li[data-id]. The row dataset then supplies the id, and the handler can open that lesson.

This survives rows added later because the listener is on the parent, not on the rows. A button that creates a new li and appends it does not need to register anything. The next click still bubbles to the same function. A contains check makes sure the match is inside this list, so a nested widget with its own data-id cannot be claimed by accident. One listener also means one place to remove the behavior when the widget is destroyed.

Syntax & Parameters

Syntax
parent.addEventListener("click", (event) => {
  const row = event.target.closest("[data-id]");
  const id = row?.dataset.id;
});

Example

Interactive preview available
app.js
'use strict';

const list = document.querySelector('#lesson-rows');
const log = document.querySelector('#open-log');
const add = document.querySelector('#add-row');

function writeLog(message) {
  if (log !== null) {
    log.textContent = message;
  }
  console.log(message);
}

if (list !== null) {
  list.addEventListener('click', (event) => {
    if (!(event.target instanceof Element)) {
      return;
    }
    const row = event.target.closest('li[data-id]');
    if (row === null || !list.contains(row)) {
      return;
    }
    const id = row.dataset.id ?? '';
    const titleNode = row.querySelector('span');
    const title = titleNode === null ? id : titleNode.textContent.trim();
    writeLog(`Opened ${id}: ${title}`);
  });
}

let extra = 0;
if (add !== null && list !== null) {
  add.addEventListener('click', () => {
    extra += 1;
    const item = document.createElement('li');
    item.dataset.id = `extra-${extra}`;
    const label = document.createElement('span');
    label.textContent = `Extra row ${extra}`;
    const button = document.createElement('button');
    button.type = 'button';
    button.textContent = 'Open';
    item.append(label, button);
    list.append(item);
    writeLog(`Added extra-${extra}. The same listener covers it.`);
  });
}

writeLog('Listener attached to #lesson-rows.');

Expected Output

On load, #open-log:
Listener attached to #lesson-rows.

After clicking Open on the Scope row:
Opened js-const-let-scope: Scope

After clicking Add row:
Added extra-1. The same listener covers it.

After clicking Open on that new row:
Opened extra-1: Extra row 1

Line-by-Line Walkthrough

  1. One click listener is added to #lesson-rows. The rows themselves do not get their own listeners.
  2. writeLog stores the message with textContent and prints it, and it does nothing to the log node when that node is missing.
  3. The handler ignores the event when target is not an Element, which keeps the closest call safe.
  4. closest starts at the clicked node and walks upward until it finds an li that has data-id.
  5. If that row is missing, or if it is not contained by this list, the handler returns without opening anything.
  6. dataset.id reads the data-id value. A span inside the row supplies the visible title, with the id as a fallback.
  7. The log line names both the id and the title, so a click on the Open button and a click on the label share one path.
  8. The add button builds a new li with createElement, sets dataset.id, and appends a label and a type button.
  9. That new row is appended after the parent listener already exists, and the log says the same listener covers it.
  10. On load the script logs that the listener is attached, before any row has been clicked.

Common Pitfalls & Security

Delegation only sees events that bubble. focus does not bubble, while click does, so this pattern fits clicks and not every event. closest can walk out of your widget if the selector is too broad and you forget the contains check. dataset values are strings a page author controls here, but if an id is ever copied into HTML you are back to an injection problem. Keep the id in a property or in the log as text.

  • event.target.closest("li") without a data-id test can match a list item that is only a heading.
  • Skipping list.contains(row) lets a nested list satisfy the same selector and open the wrong record.
  • Binding the listener inside the add-row handler stacks a new parent listener on every click. Bind it once.
  • A button inside the row still needs type="button" when the list sits in a form, or the click submits.
  • log.innerHTML = id parses markup. An id equal to the untrusted string <img src="x" alt="untrusted"> is an XSS hole. Use textContent.

Best Practices & Modern Standards

Listen on the stable parent, select the row with closest and a precise selector, and read data-id from dataset. Confirm the row is inside the parent before you act. ES2024 does not change bubbling or closest. The pattern stays the right default for lists that grow, including rows rendered after a fetch.

Create new rows with createElement and set dataset in the same function, so the selector the listener expects is guaranteed. Use one listener for the life of the widget and remove it if the widget is torn down. Keep buttons as type button. Log and render ids as text, never as HTML, even when the id looks like a slug you generated yourself.

Real-World Use

An instructor roster lists one row per lesson, and each row has an Open button. Instead of binding a handler while creating every row, the dashboard listens once on the list. A click reports the data-id and the lesson title. When a new lesson is published, the page appends a row and the existing listener opens it.

That matters after a filter redraw too. The list node stays in the page, the rows are replaced, and the listener does not have to be reattached. The open log is plain text, so a title that includes a tag cannot change the dashboard markup.

Frequently Asked Questions

Why does a new row still respond to clicks?

The listener is on the parent list, and click events bubble from the new row up to that list. The row does not need its own listener. closest finds the row from whatever child was clicked.

What does closest return if I click the list background?

It returns null when no ancestor matches li[data-id]. The handler should return in that case. Do not assume every click inside the parent landed on a row.

Why read dataset instead of parsing the label?

The visible label can change or repeat. data-id is the stable key. dataset.id maps from the data-id attribute, and the value is always a string.

Does this work for events that do not bubble?

No. Delegation depends on the event reaching the parent. click bubbles, so this pattern fits row actions. For an event that does not bubble you need a listener on each node or a different event.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…