Spot the bug - #110: Todo List

My todo list deletes the wrong item every single time, help

const list = document.getElementById('todoList');

function addItem(text) {
  const li = document.createElement('li');
  li.textContent = text;

  const removeBtn = document.createElement('button');
  removeBtn.textContent = 'Remove';
  removeBtn.addEventListener('click', () => {
    list.removeChild(li.parentElement);
  });

  li.appendChild(removeBtn);
  list.appendChild(li);
}

addItem('Buy milk');
addItem('Walk dog');
addItem('Write code');

Reply with what is broken and how you would fix it.

removeChild(li. parentElement) removes the list itself, not the li. Should just be list. removeChild(li), since list and li are already in scope from the closure.

Spot the Bug answer: The click handler removes li.parentElement (the list itself) instead of the li item that contains the clicked button

The fix:

list.removeChild(li);

Why:
li.parentElement refers to the ul (list), not the individual todo item, so calling removeChild on it tries to remove the whole list from its parent instead of removing the specific li. The handler should remove li directly since that is the element containing the button that was clicked.

First-answer leaderboard

  1. @kirupa - 3 (firsts) :trophy:
  2. @emmawalter5 - 1 (first)