0

I've set up a fairly simple app that has an input for tasks and will add the tasks typed into it to a task list.

HTML

<!DOCTYPE HTML>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Flatiron Task Lister</title>
  <link rel="stylesheet" href="./style.css">
</head>
<body>
  <div id="main-content">
    <h1>Task Lister Lite™️</h1>

    <form id="create-task-form" action="#" method="post">
      <label for="new-task-description">Task description:</label>
      <input type="text" id="new-task-description" name="new-task-description" placeholder="description">
      <input type="submit" value="Create New Task" id="submit">
    </form>

    <div id="list">
      <h2>My Todos</h2>
      <ul id="tasks">
      </ul>
    </div>

    <script src="./src/index.js"></script>
  </div>

</body>
</html>

index.js


document.addEventListener("DOMContentLoaded", () => {
  const task = document.getElementById("new-task-description")
  const submit = document.getElementById("submit");
  const list = document.getElementById("list");

  submit.addEventListener("click", function(event) {
    event.preventDefault();
    let todo = task.value;
    list.innerHTML += `<div id="list-${todo}"><li>${todo}<button>X</button></div>`;
  });
});

As you can see, I set it up so each task gets a unique id in a div tag and also an x button in case somebody would like to delete the task. I cannot figure out how to add an event listener to the X button because it doesn't exist when the script is run. Any ideas on how to do this or maybe a simpler away to achieve this would be much appreciated.

  • 1
    Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) Note there is a non-jQuery solution [here](https://stackoverflow.com/a/27373951/215552). – Heretic Monkey Jan 23 '20 at 19:27

1 Answers1

0

Here a simple method how you can create dynamic elements and add EventHandler to them:

const newElement=document.createElement("span");
newElement.innerHTML="Hello World, I am clickable!";
newElement.classList.add("sp");
newElement.addEventListener("click", ()=>{
  prompt("Am I cute?");
});

document.body.appendChild(newElement);
.sp{
  position: relative;
  background-color: #eee;
  border-radius: 4px;
  padding: 6px 10px;
  cursor: pointer;
}
<br><br>
Adnane Ar
  • 683
  • 7
  • 11