I have made a to do list app, everything is working but if i delete all the element present in the list manually the delete all button will still appear on the screen obviously. I can't seem to be able to find a soultion... Maybe i should make an array of every li element that gets created but i don't really know how go about that...
const input = document.querySelector("#input");
const button = document.querySelector("#btn");
const list = document.getElementById("list");
const deleteAllButton = document.getElementById("deleteall")
form.addEventListener("submit", (e) => {
e.preventDefault();
let inputvalue = input.value;
if (!inputvalue) {
alert("Inserisci un task");
} else {
let task = document.createElement("li");
let taskinput = document.createElement("input");
taskinput.disabled= true;
taskinput.value = inputvalue;
list.appendChild(task)
task.appendChild(taskinput)
input.value = ''
let editButton = document.createElement("button");
let editText = document.createTextNode("Edit")
editButton.type = "button"
editButton.id ="edit"
editButton.appendChild(editText)
task.appendChild(editButton)
let deleteButton = document.createElement("button");
let deleteText = document.createTextNode("Delete")
deleteButton.type = "button"
deleteButton.id= "delete"
deleteButton.appendChild(deleteText)
task.appendChild(deleteButton)
deleteAllButton.style.display= "block";
deleteAllButton.addEventListener('click', () => {
deleteAllButton.style.display= "none"
list.innerHTML = '';
})
editButton.addEventListener("click", () =>{
taskinput.disabled = false
editButton.style.display= "none"
deleteButton.style.display= "none"
let saveButton = document.createElement("button");
let saveText = document.createTextNode("Save")
saveButton.type = "button"
saveButton.id ="save"
saveButton.appendChild(saveText)
task.appendChild(saveButton)
saveButton.addEventListener("click", () => {
console.log(taskinput.value)
if(!taskinput.value){
alert("Input field is empty")
}else{
taskinput.disabled = true;
editButton.style.display= "block"
deleteButton.style.display= "block"
saveButton.remove()
}
})
})
deleteButton.addEventListener ('click', ()=>{
task.remove()
console.log(task)
})
}
})
CodePudding user response:
You can check the length of the list (list.childNodes) before displaying the delete all button. If the length of the list is 0, then you can hide the delete all button.
//...
list.appendChild(task)
//...
if (list.childNodes.length > 0) {
deleteAllButton.style.display = "block";
} else {
deleteAllButton.style.display = "none";
}
deleteAllButton.addEventListener('click', () => {
deleteAllButton.style.display= "none"
list.innerHTML = '';
})
//...
deleteButton.addEventListener ('click', ()=>{
task.remove()
if (list.childNodes.length === 0) {
deleteAllButton.style.display = "none";
}
})
//...