I’m making a task management system, but I can’t seem to figure out how to check if a specific button was pressed from a task, and delete that same task with the button that was pressed.
document.addEventListener("DOMContentLoaded", function() {
console.log("1");
document.querySelector("#add-new-btn") ? .addEventListener("click", function() {
const iValue = document.querySelector("input") ? .value;
if (iValue == "") {
console.warn("All fields must be filled out");
alert("Please enter a task description!");
} else {
const taskDiv = document.createElement("div");
taskDiv.className = "task"
const taskDesc = document.createElement("p");
taskDesc.innerHTML = iValue;
taskDiv.appendChild(taskDesc);
const taskCompBtn = document.createElement("button")
taskCompBtn.textContent = "Complete"
taskCompBtn.id = "compBtn"
taskDiv.appendChild(taskCompBtn);
const taskContainer = document.querySelector(".tasks-container");
taskContainer ? .appendChild(taskDiv);
}
});
document.querySelector("#compBtn").addEventListener("click", function() {
console.log('Completed task')
})
});
<body>
<div class="header">
<h1>To-do list app</h1>
<p>An amazing to-do list application</p>
</div>
<div class="add-new-container">
<h3>Add new Task</h3>
<input type="text" placeholder="Description..">
<button id="add-new-btn">Add Task</button>
</div>
<div class="tasks-container">
<!-- <div class="task">
<p>[EX] Wash the dog</p>
<button>Complete</button>
</div> -->
</div>
<script src="main.js"></script>
</body>
I’ve tried using an id in the past, and assigning an id to each task, but I wasn’t quite sure how to check the id’s properly (if that makes sense).
3
Answers
add your event listener when you are creating the task (in the else portion of your code)
Your problem is that when you try to add a click listener to the button, the button itself does not exist.
Common solutions to this problem are:
Here is an example:
This snippet:
So, every time you click something, the document click listener is executed. If you clicked on a button with the class compBtn, the parent element of the button itself is removed from the DOM. You don’t need the button to exist on page load.
Please, remember that you need to change id to class for this to work:
You can use this code. First when you select a DOM element make sure it is already appended. I also remeved the id on btn otherwise it won’t be unique and replaced with class. Then I loop through the btns to check for click and then select the parent element that contains both the task and btn to be removed.
.