0

I am creating a simple TodoList for creating and deleting tasks:

let btn= document.getElementById("createButton");
let tasks= [];

//function for creating task. This is working fine
btn.addEventListener('click', function(){
    let taskName= document.getElementById("taskName").value;
    let startTime= document.getElementById("startTime").value;
    let endTime= document.getElementById("endTime").value;
    // console.log(taskName, startTime, endTime);
    let currTask= {
        name: taskName,
        start: startTime,
        end: endTime
    }
    tasks.unshift(currTask);
    let createdTask= document.createElement('div');
    createdTask.id= taskName;
    createdTask.classList.add("mrg-auto");

    createdTask.innerHTML= `
    <p>Task name: ${taskName}</p>
    <p>Start time: ${startTime}</p>
    <p>End time: ${endTime}</p>
    <input type="submit" class="deleteButton" value="Delete">`;
    
    document.getElementsByTagName("main")[0].append(createdTask);
    // console.log(tasks.length);
})

//code from here does not work. This is the code for deletion
var del= document.getElementsByClassName("deleteButton");

for(let i=0;i<del.length;i++){
    del[i].addEventListener('click', function(){
        for(var j=0;j<tasks.length;j++){
            if(tasks[j].name==del[i].id){
                tasks.splice(j, 1);
                console.log("hello");
                break;
            }
        }
    });
}

I am not able to delete task from array using class name and splice function. Where am I going wrong?

4
  • 1
    Create a complete snippet with tools [<>] thanks. Commented Sep 2, 2021 at 11:31
  • Please include the necessary code for a Minimal, Reproducible Example. We cannot magically guess what you're doing / trying to do. Commented Sep 2, 2021 at 11:32
  • Done. Pls check now. Commented Sep 2, 2021 at 12:35
  • You haven't created a proper snippet - I'm going to edit to convert your code into a snippet; please add your html to the snippet. Commented Sep 2, 2021 at 15:19

1 Answer 1

1

How about instead of looping the elements, but attach the event handler to document. Like so:

document.addEventListener('click',function(e){
   if(e.target && e.target.className  == 'deleteButton'){
     e.target.parentNode.parentNode.removeChild(e.target.parentNode)
     tasks.splice(tasks.findIndex(({name}) => name == e.target.parentNode.id), 1);
   }
});

PS: Note that giving id as taskName createdTask.id= taskName;may not be the best practice.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.