0Pricing
JavaScript Academy · Lesson

Dynamic Lists with Delegation

Manage events for elements added at runtime.

Dynamic Lists with Delegation is a free JavaScript Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Dynamic Element Problem

When you attach listeners directly to elements, any element added to the DOM after setup has no listener. Delegation solves this because the parent listener catches events from future children too.

Direct Listeners Break

Here, a listener is added to existing items. A newly appended item gets nothing and stays dead.

document.querySelectorAll(".item").forEach((el) =>
  el.addEventListener("click", handle)
);
list.appendChild(newItem); // newItem has NO handler

Delegation Just Works

With a delegated listener on the parent, the new item is handled automatically. No re-binding needed after each insert.

list.addEventListener("click", (e) => {
  const item = e.target.closest(".item");
  if (item) console.log("Clicked", item.dataset.id);
});
list.appendChild(newItem); // works immediately

Adding Items

Build new elements and append them. Because the parent already delegates, they are interactive the moment they appear.

function addItem(text) {
  const li = document.createElement("li");
  li.className = "item";
  li.textContent = text;
  list.appendChild(li);
}

Removing Items

Deletion is also clean. A delegated handler can detect a delete button inside the row and remove the row.

list.addEventListener("click", (e) => {
  if (e.target.matches(".delete-btn")) {
    e.target.closest(".item").remove();
  }
});

Distinguishing Sub-Actions

A row may have several interactive parts. Use matches() or closest() to tell which one was clicked, then branch.

list.addEventListener("click", (e) => {
  if (e.target.matches(".edit-btn")) edit(e);
  else if (e.target.matches(".delete-btn")) del(e);
});

Rendering From Data

A common pattern: keep state in an array, render rows from it, and delegate clicks. Re-rendering replaces the children, but the single parent listener survives untouched.

function render(items) {
  list.innerHTML = items
    .map((i) => "<li class=\"item\" data-id=\"" + i.id + "\">" + i.name + "</li>")
    .join("");
}

No Cleanup Headaches

With per-element listeners you must remember to removeEventListener before deleting nodes to avoid leaks. Delegation removes that burden: deleting a child does not orphan any listener.

Toggling Classes

Delegation pairs well with class toggles for selection states. The handler finds the row and flips a class.

list.addEventListener("click", (e) => {
  const row = e.target.closest(".item");
  if (row) row.classList.toggle("selected");
});

Reading Stable Identity

Since DOM nodes get replaced on re-render, never store references to them. Store a stable id in data-id and look up your data model by that id inside the handler.

const id = e.target.closest(".item").dataset.id;
const record = state.find((r) => r.id === id);

Input Events Too

Delegation is not limited to clicks. You can delegate input or change events for dynamically added form fields the same way.

form.addEventListener("input", (e) => {
  if (e.target.matches(".qty")) recalc(e.target);
});

Quick Check

Dynamic lists and delegation.

Recap

Delegation shines with dynamic lists: one parent listener handles current and future children, survives re-renders, and needs no per-node cleanup. Use matches() and closest() to branch on sub-actions, and store stable ids in data-* so handlers can find your data model.

Frequently asked questions

Is the “Dynamic Lists with Delegation” lesson free?

Yes — the full text of “Dynamic Lists with Delegation” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Dynamic Lists with Delegation”?

Manage events for elements added at runtime. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start JavaScript Academy?

No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Dynamic Lists with Delegation” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this JavaScript Academy lesson?

Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The Capture and Bubble Phases
  2. Event Delegation Pattern
  3. Dynamic Lists with Delegation
  4. Custom Events
← Back to JavaScript Academy