One listener can serve changing rows
When a row is rebuilt, its old DOM element is gone. Creating a new listener callback and registering it on a long-lived container on every render accumulates handlers. Re-registering the exact same function with the same event type and capture setting is ignored, but a newly created arrow function is a different listener. A useful pattern is event delegation: register one listener on the list and identify the clicked row's action.
Click events normally bubble from the target up through its ancestors. event.target identifies the originating node; event.currentTarget is the element whose listener is currently running. closest("button[data-id]") finds a matching button at or above a nested target, such as a span inside the button. A data-id HTML attribute is read as button.dataset.id, always text.
Guard the target before calling element methods: event.target instanceof Element asks whether it is an element. instanceof checks an object's relationship to a constructor, not a string type name. Our capstone uses this on DOM events and Error values; it does not replace validation of unknown JSON.
Use the data id to look up a validated record in state. Do not read a title out of the row and treat it as the record. Titles may repeat, text may change, and displayed values are formatted. On removal, move focus to a stable control so keyboard users are not left on a disappeared button. Keep user text in textContent.
Predict and trace
Write the output before running. Follow the values through each call; if your prediction differs, identify the first step that surprised you.
function findAction(books, dataset) {
return books.find(book => book.id === dataset.id);
}
const books = [
{ id: "js", title: "Notes" },
{ id: "web", title: "Notes" }
];
console.log(findAction(books, { id: "web" }).id);
console.log(findAction(books, { id: "missing" }) === undefined);Check your prediction
web
trueTwo books have the same title, so the id determines which one the action belongs to.
Why a listener inside render accumulates
EventTarget is the browser interface behind elements, and it also exists in console JavaScript, so you can watch listeners pile up without a page. Predict both counts.
const list = new EventTarget();
let handled = 0;
function renderWithListener() {
// A new arrow function is created on every call.
list.addEventListener("click", () => {
handled += 1;
});
}
renderWithListener();
renderWithListener();
renderWithListener();
list.dispatchEvent(new Event("click"));
console.log(`one click handled ${handled} times`);
const onClick = () => {
handled += 1;
};
const other = new EventTarget();
handled = 0;
other.addEventListener("click", onClick);
other.addEventListener("click", onClick); // the same function: ignored
other.dispatchEvent(new Event("click"));
console.log(`same function registered twice: handled ${handled} time`);Check your prediction
one click handled 3 times
same function registered twice: handled 1 timeEach call to renderWithListener made a different arrow function, so the list kept all three and ran all three for one click. Registering the same function again is ignored. In a real page the first case is a bug that grows with every render: the exercise below makes you find it.
Practice on a changing list
Press Run webpage to preview. Each run starts fresh. Edits are not saved automatically.
Press Run webpage. Click the nested Remove text on the first row, then remove the second row using Tab and Enter. Reset the list, then remove again. The same list listener should still work after rows are rebuilt. The heading and status are outside the list; clicking them must not remove anything.
button[data-id] is a selector for a button carrying a data-id attribute. closest searches the clicked element and its ancestors for that match. The HTML contains a span inside each button so you can see why the click target is not always the button itself. event.currentTarget remains the list that owns the listener.
The render function creates nodes and assigns textContent, as the beginner planner did. Keep the removeById rule separate from those DOM operations: it is a plain function that a console test could check.
Build it yourself
Bug hunt: two actions per row
This page is a study-task list. Each row has a Done button (marks the task done and hides that button) and a Delete button, and one delegated listener should handle both. It has two defects that a quick test misses. Run it and try:
- Click the word "Done" on the first row. Nothing happens.
- Click Reset tasks twice, then tab to a Delete button and press Enter. The status reports several handled actions for one key press.
Fix the page so that clicking anywhere on a button, its label included, performs that button's action on that row's task. Each click or key press must count as one handled action however many times you reset. Clicks on a row's text, on the list outside a button, or on the heading must do nothing. The working lab above handles a single action; here the handler must also read which action the button stands for.
Press Run webpage to preview. Each run starts fresh. Edits are not saved automatically.
Hint 1: the idea
The two symptoms have two causes. One is where the listener is registered: render runs after every change. The other is which element the handler reads its id from: the clicked element is often the <span>, not the button.
Hint 2: a first step
Fix the counting first: decide where a listener that should exist exactly once belongs, given that render runs after every change. Move it, then reset three times and press Enter on a button: the handled count should go up by one. The label click still fails; that is the second fix, and it decides which element both action and id are read from.
Show one solution
Press Run webpage to preview. Each run starts fresh. Edits are not saved automatically.
The list element itself survives every render; only its rows are rebuilt. Registering inside render added a new arrow function each time, and every one of them ran on each click, so one press was handled once per earlier render. Registered once, outside render, the listener runs once per click forever. event.target.dataset read action and id from whatever was clicked, which for a label is a <span> with no data, so the click was ignored. event.target.closest("button[data-action]") walks up to the button that owns the click, and both values are then read from that one element, so a Done label can never be paired with another button's id. list.contains(button) keeps the rule "only this list's buttons are its actions". Clicking a row's text finds no button above it and does nothing. The instanceof Element guard comes first because closest exists only on elements.
Explain before moving on
Where should a delegated listener be registered? Why does closest handle a nested button label better than reading target.dataset directly?
Completion is saved in this browser only. It does not measure mastery.