0

I am just getting started off with javascript and I am trying to build a To-Do app. My problem is that I have a clear all button which when clicked removes all the tasks from the list. And to make it work, I have written this function(see below).

function clearAll(e){
e.preventDefault()

let allItems = todoList.childNodes
allItems.forEach(function(item){
   todoList.removeChild(item)
})
      
  }
Here the

todoList

is a ul element to which the divs(tasks) are appended dynamically. The result is that I am getting alternate items removed when I click the button. How do I fix this?

Shreeja Geeda
  • 37
  • 1
  • 6

2 Answers2

4

You don't need all these complex things when you can just remove the innerHTML!

todoList.innerHTML = ""
Aviral
  • 218
  • 2
  • 12
  • 1
    Interesting performance analysis comparing `removeChild` to `innerHTML`: https://rusingh.com/javascript-benchmark-removechild-vs-innerhtml/ I was surprised to see that `innerHTML` is significantly slower (65% slower in this test) – David784 Oct 16 '21 at 13:58
  • According to [this site](https://www.javascripttutorial.net/dom/manipulating/remove-all-child-nodes/) it is possible that this method may not remove event handlers, which could result in memory leaks. – Flightkick Aug 10 '22 at 20:44
3

The following removeAllChildNodes() function removes all the child nodes of a node:

function removeAllChildNodes(parent) {
    while (parent.firstChild) {
        parent.removeChild(parent.firstChild);
    }
}
const container = document.querySelector('#container');
removeAllChildNodes(container)
Yasin Br
  • 1,675
  • 1
  • 6
  • 16