Task List. Remove Task Button

Currently, I am in the process of creating a to-do list. I would like to incorporate a button with the class .cancel-task that will remove the specific item associated with that button. However, when attempting to use addEventListener, I encountered an error stating "it's not a function". Can someone please guide me on how to achieve this by utilizing the id attribute that I assigned earlier to tasks? Additionally, I would appreciate instructions on how to delete 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}" class="item-task">
        <span>${taskObj.task}</span>
        <button class="cancel-task">
            <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 class="todo_wrapper">

    <ul class="todo_tasks-wrapper">

    </ul>

    <form class="control" action="">
        <label class="todo_label-form" for="task">
            <input class="todo_input" id="task" type="text" placeholder="Enter new task" maxlength="30">
            <input class="todo_submit" type="submit" value="+">
        </label>
    </form>

</div>

Answer №1

To detect when a button with the class "cancel-task" is clicked inside the todo_tasks-wrapper element, you can add an onclick listener and iterate through the event path to find matching elements.

For example:

todoTaskWrapper.addEventListener("click", (event) => {
  for (let el of event.composedPath()) {
    if (el.matches && el.matches("button.cancel-task")) {
      console.log(el, "is the button clicked")
      console.log(el.parentNode, "is the li element");
      el.parentNode.remove();
    }
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular: it is impossible to access property 'x' as it is undefined

I am facing an issue where I keep getting the error message Cannot read property 'id' of undefined in my HTML component. <button (click)="getRecipeDetails()">Show</button> <div> <div [innerHTML]="recipeIn ...

There was an issue when attempting to upload a single JSON file as input for the workitem in DesignAutomation

My goal is to compile a design automation web application using an input file, such as an RVT and Json file. However, I am encountering an issue where I need to pass only a Json file as input for workItem in ForgeDesignAutomation.js. In the code snippet be ...

Utilizing jQuery to eliminate a script function from an external webpage

Currently, I am utilizing a ColdFusion script to load an external page within the container tag. This external page contains a sorting function defined as: function sorting(sortid). However, this function's sorting criteria constantly leads to errors ...

Configuring SameSite cookie attributes in NuxtJS

Currently, as I dive into learning Nuxt.js, I have successfully assigned some data to localStorage using localStorage.getItem() and localStorage.setItem(). The process worked quite smoothly initially until I encountered a warning message indicating: Cookie ...

Guide on adding the contents of non-empty <td> tags using Javascript or JQuery

My goal is to calculate the total sum of all the HTML content within <td> elements with the attribute name='gross_val'. Here are the <td> elements I am working with: <tr><td name="gross_val" align="right" title="gross_val1" ...

Converting a deeply nested dictionary into a pandas dataframe

I've been struggling to convert a deeply nested dictionary into a pandas DataFrame. I attempted to use a recursive function, similar to the one below, but my issue is that I lose track of the previous key while iterating over a KEY. I also experimen ...

What could be causing the sudden increase in time taken for AJAX requests, going from a mere 2 milliseconds to over 50 milliseconds?

Recently, I developed a script using jQuery for AJAX that allows me to "ping" the server and measure the time it takes for my AJAX requests to complete. var start = Date.now(), end = 0; setInterval(function() { $.ajax('', { complete ...

Vue.js not accepting an object as input value

I am working with an input type text in my vue js application. This is the initial code snippet: <input type="text" v-model="answer[index]" > Here is the updated code: <table> <tr v-for="(question_overall, index) in questions"> ...

Anticipated a task or procedure but encountered an expression instead

I'm encountering an issue with the following code snippet. JShint is flagging it with "Expected an assignment or function and instead saw an expression". function checkVal(inputField) { ( inputField.val() === '' ) ? inputField.prev( ...

The text inside the table-column is not automatically resizing to fit the

View Screenshot Note: This application does not work in Internet Explorer. I need a solution that is compatible with Chrome and Firefox. I am using dynamic code (velocity-spring) to create an HTML table. The number of columns varies, so I cannot set widt ...

Is it possible to use null and Infinity interchangeably in JavaScript?

I've declared a default options object with a max set to Infinity: let RANGE_DEFAULT_OPTIONS: any = { min: 0, max: Infinity }; console.log(RANGE_DEFAULT_OPTIONS); // {min: 0, max: null} Surprisingly, when the RANGE_DEFAULT_OPTIONS object is logged, i ...

What is the process for setting up a server with Node.js?

After diving into my nodejs studies, I hit a roadblock at the point where I was supposed to create a server. Here's the code snippet for this particular script: var http = require('http'); // Import Node.js core module var server = http.cre ...

Exploring the capabilities of Node.js functions

I'm currently exploring Node.js and struggling to understand how functions are created and used. In my code snippet: var abc={ printFirstName:function(){ console.log("My name is abc"); console.log(this===abc); //Returns true ...

Using JavaScript or Node.js, learn how to update links with a common header file

I need help updating links on my website for different pages. My website has a common header file with a navbar that includes a dropdown menu for selecting languages. Currently, I am using the same header file for all pages. When a language is selected fr ...

Is it possible to retrieve the object from a forEach loop?

Can an object be built using the results of a forEach loop? Here's my current approach: const data = {} object.rules.forEach(rule => { data[rule.name] = { body: [], type: rule.type } }) This is how I'd prefer to do it: const newData = obj ...

Trigger a click event on a nested Angular 13 component to remove a class from its grandparent component

In my Angular 13 project, I am working with 3 components: Child Component : Burger-menu Parent Component : Header Grand-Parent Component : app.component.html Within the burger-menu component, there is a close button. When this button is clicked, I want t ...

Access the array values by their respective keys in an object that is returned from a custom JavaScript file utilizing the Node.js file system

I recently came across a config file with a unique format, as shown below: define([], function () { return { productItems: { item1: ['Apple', 'Ball', 'Car'], item2: [&apo ...

Refreshing select2 dropdown options dynamically with AJAX updates

I have a select dropdown for locations that is initialized using select2 on page load. I am looking to dynamically update the data in the dropdown at regular intervals using ajax calls. However, when I attempt to update the data in select2, the dropdown ...

PHP-powered interactive web application driven by REST API

I am currently in the process of creating a REST-Centric web dashboard using PHP. My main goal is to ensure that data is exchanged solely through REST calls without any direct database connections. I have explored various frameworks such as slim, silex, ...

Decoding JSON in C# without specifying a variable name

I'm having trouble converting a Json String to an object, as I am only receiving 0 and null values in return. Below is the code snippet I'm using: string result = "[{\"page\":1,\"pages\":1,\"per_page\":\"50&bs ...