Issue with delete button in js

I made a codepen that is named Altering DOM with JS demo (Adding and removing elements) but I have an issue (bug) on Delete all items button
I tried hard coding this button but the button does not delete the list items by one time
Here is the link to the code and you will see in js section my coding in Delete all items button
https://codepen.io/abdulrahman-coder/pen/bGwLEKO

The bug is coming from the for loop:

// Remove All Items
removeAll.addEventListener("click", (a) => {
  if (ul.children.length) {
    for (let i = 0; i < ul.children.length; i++) {
      let allNodes = ul.children[i];
      ul.removeChild(allNodes);
    }
  }
});

If you have two list items in your <ul>, the code would do this:

  • i=0 --> remove one item from ul.children --> ul.children.length becomes 1
  • i=1 --> loop stops because 1 isn’t smaller than ul.children.length

That’s why one item is still left. A better approach than a for loop would be to turn ul.children into an array and then run a .forEach on it to remove the list items.

Or you could just set ul.innerHTML = ''.

1 Like

Here’s my hint. ul.children gives you all of the li nodes in the ul. So you can just loop through that and remove each one. Ahh, I see @jsdisco has beaten me to the punch. And I agree, setting innerHTML to an empty string is probably the easiest/best way.

1 Like