skip to Main Content

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


  1. add your event listener when you are creating the task (in the else portion of your code)

     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);
                
                taskCompBtn.addEventListener("click", function() {
                console.log('Completed task');
                taskContainer?.removeChild(taskDiv);
                  console.log('Deleted task');
                });
            }
        });
       
     <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>
    Login or Signup to reply.
  2. 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:

    1. Attach the event listener to each button just after creation.
    2. Attach the event listener to a higher-level element, like the whole document.

    Here is an example:

    document.addEventListener("click", function(event) {
      if (event.target.closest(".compBtn")) {
        (function() {
          this.parentNode.remove();
        }).call(event.target, event);
      }
    });
    

    This snippet:

    1. Adds a click event listener to the document.
    2. Checks if the element you clicked has the class compBtn (I am using a class because you cannot have multiple elements with the same ID in your DOM).
    3. Defines a function.
    4. Inside that function, removes the parent element of the clicked one.
    5. Calls the function, passing the clicked element as the context.

    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:

    // REMOVE --> taskCompBtn.id = "compBtn"
    taskCompBtn.className = "compBtn"; // <-- ADD
    
    Login or Signup to reply.
  3. 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.

    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.classList.add('compBtn')
                taskDiv.appendChild(taskCompBtn);
                const taskContainer = document.querySelector(".tasks-container");
                taskContainer.appendChild(taskDiv);
                const btns = document.querySelectorAll(".compBtn")
                btns.forEach(btn=>btn.addEventListener('click', function () {
                    let tasktoDelete = btn.parentElement
                    tasktoDelete.remove()
                }))
    
            }
        });
    });
    <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>

    .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search