Home > Back-end >  ToDo List. Delete task button
ToDo List. Delete task button

Time:10-02

I am trying to build todo list and I like to put on button(.cancel-task) action which remove exactly item which connected with that button, but when I try to put addEventListener I meet error like "its not a function". Please explain me how to make it with using attribute id which I add before for tasks and also how to remove this item from local storage. Thank you, for your attention.

const taskList = document.querySelector(".todo_tasks-wrapper");
const formTodo = document.querySelector(".control");
const inputTask = document.querySelector(".todo_input");
const btnDeleteTask = document.querySelectorAll(".cancel-task");

const taskKeeper = [];
let taskIdCounter = 0;

const data = JSON.parse(localStorage.getItem("tasks"));

const updateHtml = (taskObj) => {
    const newLi = document.createElement("li");
    newLi.innerHTML = `<li id="${taskObj.id}" >
        <span>${taskObj.task}</span>
        <button >
            <img src="assets/todo-cancel.png" alt="Cancel">
        </button>
    </li>`;
    taskList.append(newLi);
}

const newTask = (info) => {
    taskIdCounter  = 1;
    const taskObj = {
        task: info,
        id: taskIdCounter,
    };
    taskKeeper.push(taskObj);
    localStorage.setItem("tasks", JSON.stringify(taskKeeper));
    updateHtml(taskObj);
};

formTodo.addEventListener("submit", event => {
    event.preventDefault();
    const info = inputTask.value.trim();
    if(info.length !== 0) {
        newTask(info);
        inputTask.value = "";
        inputTask.focus();
    }
});

if(data !== null) {
    for(let item of data) {
        updateHtml(item);
    }
}

        <div >

    <ul >

    </ul>

    <form  action="">
        <label  for="task">
            <input  id="task" type="text" placeholder="Enter new task" maxlength="30">
            <input  type="submit" value=" ">
        </label>
    </form>

</div>

CodePudding user response:

You can use a onclick listener on the todo_tasks-wrapper element and check every element inside the event path to match the criterias.

Example:

todoTaskWrapper.addEventListener("click", (event) => {
  for (let el of event.composedPath()) {
    // window and document have no matches function, but they are included in the path
    if (el.matches && el.matches("button.cancel-task")) {
      console.log(el, "is the button clicked")
      console.log(el.parentNode, "is the li element");
      // remove it
      el.parentNode.remove();
    }
  }
});
  • Related