I am trying to get the ID of the task when I click edit. The reason for this, is I want to use the ID from the data-id="${task.id}" that identifies each task created.
I have created a function that renders the task and it works:
taskArray.forEach((task) => {
let divEl = document.createElement("div");
divEl.classList.add("task-flex");
divEl.innerHTML = `<div class="task-buttons">
<img src="./resources/icons/edit.png" id="edit-button" alt="Edit Buttin"/>
<img src="./resources/icons/bin.png" id="remove-button" alt="Bin Buttons" />
<img src="./resources/icons/completed-task.png" id="complete-button" alt="Complete Task Button" />
</div>
<div class="task-to-do" data-id="${task.id}" data-value = "${task.timeStamp}">
<div class="list" id="list-item-date">Due: ${task.date}</div>
<div class="list" id="list-item-task">${task.task}</div>
</div>`;
taskListEl.append(divEl);
});
This part I need assistance with.
I selected all of the edit-buttons, I then created a forEach loop for the edit-button in the forEach loop, I use the closest method to find the parent element of the edit button (editBtn)
This part is not working, its not doing anything in the console
// Event listener for edit buttons
let editBtns = document.querySelectorAll(".edit-button");
editBtns.forEach(editBtn => {
let toDoTask = editBtn.closest(".task-to-do");
let dataId = toDoTask.getAttribute("data-id");
editBtn.addEventListener("click", (event) => {
console.log(`Edit button clicked for task with data-id: ${dataId}`);
});
});
This is all one function
You can add the event listeners to each task's div (
divEl) directly in the forEach loop. But instead of assigning an id to each img, you can for example usedata-attribute to designate the actions. In your example, each icon image would get the sameidfor each task, which is not good practice. Maybe you meantclass?You would then define functions to handle edit, remove and complete actions, where the id of the task is passed as a variable from the event listener function. Here is an example: