I’m building a todo app using js, and I’ve been trying to figure out the logic behind why my deleteTask function is not working. This is my first time building a todo app (started learning web dev this March), and after searching for similar issues online I decided to ask here.
Here’s my code so far. // function to delete a task is where the trouble is, could be I’m missing a step.
I tried to apply a function like this
deleteButton.addEventListener('click', function(){
taskList.removeChild(newTask);
})
after seeing a video on Youtube where a developer was explaining how to built a todo app and this way worked for me ! But I want to figure out why my code is not running instead of using a solution that’s worked for someone else.
Below is my JS code
//selecting html elements
const taskForm = document.getElementById("taskForm");
const taskInput= document.getElementById("taskInput");
const taskList = document.getElementById("taskList");
// function to add a new task
function addTask(event){
event.preventDefault()
// new html element <li> to list our tasks
const newTask = document.createElement('li');
taskList.append(newTask);
newTask.innerHTML = taskInput.value;
taskInput.value = ' ';
// creating a delete button element
const deleteButton = document.createElement('button');
newTask.append(deleteButton);
deleteButton.setAttribute('class', 'delete-button');
deleteButton.innerHTML = "Delete";
}
// function to delete a task
function deleteTask(event){
const newTask = event.target;
taskList.removeChild(newTask);
}
// when button "add task" is clicked new task is added
const button = document.querySelector('.button');
button.addEventListener('click', addTask );
//when button "delete" is clicked a task is removed
const delButton = document.querySelector('.delete-button');
delButton.addEventListener('click', deleteTask );