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)
})
}
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?
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)
You don't need all these complex things when you can just remove the innerHTML!
todoList.innerHTML = ""