sem s sem s - 5 months ago 8
HTML Question

How to add a 'delete all button' in javascript

I'm new with javascript and i try to make a to do list for the first time. I'm trying to add a button to delete all of the tasks in a to do list. I can't find how it works.

var inputField = document.getElementById("inputField");
inputField.focus();
inputField.onkeyup = function (event) {

if (event.which === 13) {
var taak = inputField.value;

if (inputField.value.length === 0 || inputField.value == " ") {
return false;
}

addNewItem(document.getElementById("todoList"), taak);

inputField.focus();
inputField.select();
}
};


function addNewItem(list, taak) {
var date = new Date();
var id = " " + date.getHours() + date.getMinutes() + date.getSeconds() + date.getMilliseconds();

var listItem = document.createElement("li");
listItem.id = "taakItem" + id;

var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.id = "checkbox" + id;
checkBox.addEventListener("click", updateItemStatus);

var gebeurtenis = document.createElement("gebeurtenis");
gebeurtenis.id = "item" + id; // item + tijd
gebeurtenis.innerText = taak;
gebeurtenis.addEventListener("dblclick", deleteItem);

listItem.appendChild(checkBox);
listItem.appendChild(gebeurtenis);

list.appendChild(listItem);

}

function updateItemStatus() {
var checkboxId = this.id.replace("checkbox", "");
var taak = document.getElementById("item" + checkboxId);

if (this.checked) {
taak.className = "checked"; // Geeft classnaam checked voor de opmaak
} else {
taak.className = ""; // Als hij niet aangevinkt is, gebeurt er niets
}
}


function deleteItem() {
var gebeurtenisId = this.id.replace("item", "");
document.getElementById("taakItem" + gebeurtenisId).style.display = "none";
}

var deleteAll = document.getElementById("deleteAll");


i prefer to do it with an array and a loop but i don't know how. please help.

Kld Kld
Answer
 <script>
  function deleteAll(){
        document.getElementById("todoList").innerHTML = '';
    }
 </script>

 <button onclick="deleteAll()">Delete All</button>

Update

<script>   
      function deleteAll(){
           var todo =  document.getElementById("todoList");
           var lis = todo.getElementsByTagName("li");
           console.log(lis);
           while(lis.length > 0){                   
              todo.removeChild(lis[0]);
           }
        };       

</script>
Comments