Event delegation for dynamic list items in JavaScript
Intermediate · 4 min read
Lists on real pages change. A chat gets new messages, a to-do list gets new tasks, search results load more rows as you scroll. If each item needs to react to a click, you could add a listener to every one, but then each new item needs its own listener too, and it's easy to forget. Event delegation solves this with a single listener.
In this tutorial you will handle clicks on every item in a list, including items added after the code ran, using one listener on the list itself. You will also handle clicks that land on something inside an item. You should have used addEventListener and appendChild.
Events bubble up
When you click an element, the click doesn't stop there. It travels up through the element's parent, its parent's parent, and so on to the top of the page. This journey is called bubbling.
So a click on a list item also reaches the list. A listener on the list hears clicks on every item inside it, whether that item was there at the start or was added a second ago.
target and closest
The event object tells you where the click began. event.target is the deepest element under the pointer. That isn't always the item you want. Here is the list:
<ul id="list">
<li>Ojota <b>hub</b></li>
<li>Berger</li>
</ul>
Click the word "hub" and event.target is the b element, not the li. element.closest('li') fixes that: it checks the element itself, then its parent, then its parent's parent, and returns the first one that matches 'li'. If none matches, it returns null.
Here is the exercise. Try it yourself first, or read on and we will build it.
11 Event delegation for a growing list
fairHandle clicks on list items, including items added after the listener was attached, using one listener.
Stuck? Three hints, smallest first
- 1. Attach the listener to the parent. Events from the children bubble up to it.
- 2.
event.targetis what was clicked; it may be a nested element, not the item itself. - 3.
event.target.closest(‘li’)is how you find the item from whatever was actually hit.
Step 1: the approach that breaks
Start with one listener per item, to see the problem.
const list = document.getElementById('list');
const clicks = [];
for (const li of list.children) {
li.addEventListener('click', () => clicks.push(li.textContent));
}
const added = document.createElement('li');
added.textContent = 'Ibadan';
list.appendChild(added);
added.dispatchEvent(new Event('click', { bubbles: true }));
console.log(clicks.length); // 0: the new item has no listener
The loop ran once, when there were two items. The item added afterwards never got a listener, so its click is lost.
Step 2: one listener on the list
const list = document.getElementById('list');
const clicks = [];
list.addEventListener('click', (event) => {
clicks.push(event.target.tagName);
});
list.children[1].dispatchEvent(new Event('click', { bubbles: true }));
list.children[0].querySelector('b').dispatchEvent(new Event('click', { bubbles: true }));
console.log(clicks); // ['LI', 'B']
Both clicks reached the list. But the second one started on the b inside the first item, so event.target is the B, not the LI. Using event.target as if it were always the item is the mistake this step is here to show.
Step 3: find the item with closest
const list = document.getElementById('list');
const clicks = [];
list.addEventListener('click', (event) => {
const item = event.target.closest('li');
if (!item || !list.contains(item)) return;
clicks.push({ text: item.textContent.trim(), hit: event.target.tagName });
});
const click = (el) => el.dispatchEvent(new Event('click', { bubbles: true }));
click(list.children[0].querySelector('b'));
console.log(clicks[0]); // { text: 'Ojota hub', hit: 'B' }
click(list);
console.log(clicks.length); // 1: a click on the list itself is ignored
closest('li') walks up from the b and finds the first item, so the text is "Ojota hub" even though the click hit the bold word.
The guard line handles two odd cases:
!item: the click landed on the list itself, between items, so there's nolito find andclosestreturnednull.!list.contains(item):closestdoesn't stop at your list. If this list were inside anotherli, it could walk right past and return that outer item.containschecks the item really is inside our list.
Step 4: add items freely
const addItem = (text) => {
const li = document.createElement('li');
li.textContent = text;
list.appendChild(li);
return li;
};
click(addItem('Ibadan'));
console.log(clicks.at(-1).text); // Ibadan
for (let i = 0; i < 10; i++) addItem(`Stop ${i}`);
const before = clicks.length;
for (const li of [...list.children]) click(li);
console.log(clicks.length - before, list.children.length); // 13 13
The new item has no listener of its own, and it still works. Ten more items, still no new listeners, and every one of the 13 items is handled. That's delegation's other benefit: one listener costs the same whether the list has 2 items or 2,000.
The full solution
The panel builds the list, clicks an item, clicks the bold word inside the first item, adds an item and clicks it, and clicks the list background. Its checks confirm every case is handled correctly, the added item has no listener while the list has exactly one, closest returns the element itself when it matches and null when nothing does, and ten more items all work with no new listeners. Press Run, then try both buttons in the live demo.
allow-scripts only, so it cannot reach this page.const list = el('ul', { id: 'list' }, [
el('li', {}, ['Ojota ', el('b', {}, 'hub')]), // has a nested element
el('li', {}, 'Berger'),
]);
document.body.appendChild(list);
const clicks = [];
let listeners = 1; // exactly one, for the whole list
// One listener on the parent. Children's clicks bubble up to it, so items added
// later are handled with no extra work.
list.addEventListener('click', (event) => {
// target may be the <b> inside the item, so walk up to the item itself.
const item = event.target.closest('li');
if (!item || !list.contains(item)) return;
clicks.push({ text: item.textContent.trim(), hit: event.target.tagName });
});
const addItem = (text) => {
const li = el('li', {}, text);
list.appendChild(li); // no listener attached to it
return li;
};
fire(list.children[1], 'click');
console.log('clicked an existing item:', clicks.at(-1));
// Clicking the nested <b> inside the first item.
fire(list.children[0].querySelector('b'), 'click');
console.log('clicked a nested element:', clicks.at(-1), '<- closest() found the li');
const added = addItem('Ibadan');
fire(added, 'click');
console.log('clicked an item added later:', clicks.at(-1), '<- still handled');
// Clicking the list itself, but not an item.
fire(list, 'click');
console.log('clicked the list background: entries still', clicks.length);
Output
13 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 13 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('an existing item is handled', clicks[0].text, 'Berger');
test('a click on a nested element still finds the item', clicks[1].text, 'Ojota hub');
test('even though the target was the inner element', clicks[1].hit, 'B');
test('an item added afterwards is handled too', clicks[2].text, 'Ibadan');
test('with no listener of its own', added.listenerCount('click'), 0);
test('while the parent has exactly one', list.listenerCount('click'), 1);
test('there is still only one listener for the list', listeners, 1);
test('clicking the list but not an item is ignored', clicks.length, 3);
test('closest returns the element itself when it matches', list.children[1].closest('li') === list.children[1], true);
test('and null when nothing matches', list.closest('li'), null);
test('ten more items need no more listeners', (() => { for (let i = 0; i < 10; i++) addItem(`Stop ${i}`); return list.children.length; })(), 13);
test('and they all work', (() => { const before = clicks.length; for (const li of [...list.children]) fire(li, 'click'); return clicks.length - before; })(), 13);
test('still one listener', listeners, 1);
Delegation solves two problems at once. Items that do not exist yet are handled, because the listener is on the parent and the event bubbles up to it — the assertions add ten items and confirm all of them work with no new listeners. And one listener replaces however many items you have, which matters for a long list.
event.target.closest('li') is the part people leave out. target is the deepest element under the pointer, so clicking the bold text inside an item gives you the <b>, not the <li> — the assertion checks hit is 'B' while the item was still identified correctly. closest walks up from the target until it finds a match, returning the element itself if it already matches, or null. The list.contains(item) check afterwards is worth keeping too, since closest will happily walk past your container.
Common mistakes
- Using
event.targetas the item. It's whatever was clicked, which may be an element inside the item. Useevent.target.closest('li'). - Not checking for
null. A click between items has noliabove it, andclosestreturnsnull. Reading.textContentfromnullthrows. - Using
event.currentTargetinstead. During delegation,currentTargetis the list, the element the listener is attached to, not the item.
Try it yourself
- Add a small "Remove" button inside each new item. In the same list listener, if
event.target.closest('button')finds one, remove its item. - Add a
selectedclass to the clicked item and remove it from the one that had it before. - Show "clicked: Berger" in a
preelement under the list, and add a button that adds a new item with a number in its name.