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
2
Answers
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 sameid
for 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:
Here are your mistakes:
You can’t use more than one unique id on the page (id="edit-button");
To fix this point just replase
id="edit-button"
withclass="edit-button"
;This selector "document.querySelectorAll(".edit-button")" is supposed to select all elements with class name "edit-button". This won’t work in your current implementation. When you fix the #1 point it will work.
In this line
let toDoTask = editBtn.closest(".task-to-do")
you are trying to get parent element with classname "task-to-do" of the "editBtn" element. But your div with "task-to-do" classname isn’t parent of it, but a sibling one.Here is my variant:
2.Event Listeners.