0

I want to remove the first-child in an list, and this action is an onclick event of button, the onclick method is: list.removeChild(list.firstItem). However, I have to click the button twice to see the effect, WHY?

I found en example for removing first item in list by calling item.parentNode.removeChild(item). The problem is that when I change the handler method to list.removeChild(list.firstChild), I need to click twice to see the effect.

I've tried list.removeChild(list.firstChildElement) and it works as expected (first item disappear by one click), WHY this method don't need double-click compared to list.removeChild(list.firstChild) method.

Example:

  • HTML:
<ul id="list">
  <li id="first">Coffee</li>
</ul>

<button onclick="removeLi()">Remove li</button>
  • One click to see the effect:
// 1:
let item = document.getElementById("first");
function removeLi() {
  item.parentNode.removeChild(item);
}
// 2:
const list = document.getElementById("list");
function removeLi() {
  list.removeChild(list.firstChildElement);
}
  • Double click needed:
const list = document.getElementById("list");
function removeLi() {
  list.removeChild(list.firstChild);
}
ckybonist
  • 221
  • 3
  • 12