attaching an eventListener to a button that will appear when clicking another button?

so basically, I’m working on a to-do list and you have to enter a task with the button ‘enter’ then the task appears in the UI with a button called ‘delete’.

I have trouble attaching event listener to the delete button.

HTML:

<div id="container">

    <input type="checkbox" id="checkbox" name="task1"  >
    <label for="task1" id="tasks">running 10 mile</label><br>
    <button id="delete">Delete</button>
    
</div>

That’s the default one .

1 thought on “attaching an eventListener to a button that will appear when clicking another button?”

  1. Ids should be unique on the page, so I would replace id="delete" with a class because you will have multiple todo items added to your app.
    The problem with attaching an event listener on the delete buttons is they don’t exist in the DOM when the page first loads.
    We’ll need to attach the click listener on an ancestor of the todo items, and only run the delegated event handler when the delete button is clicked on.

      todoListAncestor.addEventListener('click', e => {
        document.querySelectorAll('button.delete').forEach(button => {
          if (button.contains(e.target)) {
            // ...delete the todo item
          }
        })
      })
    
    Reply

Leave a Comment