Creating & Removing Elements

Creating Elements

Example

Build elements with createElement and insert them with append, prepend, before or after:

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
</head>
<body>

<ul id="todos"></ul>
<script>
  const tasks = ["Learn HTML", "Learn CSS", "Learn JavaScript"];
  const ul = document.getElementById("todos");
  for (const task of tasks) {
    const li = document.createElement("li");
    li.textContent = task;
    ul.append(li);
  }
  const first = document.createElement("li");
  first.textContent = "Install VS Code";
  ul.prepend(first);
</script>

</body>
</html>

Result

A Small Todo App

Example

Add items, and click an item to remove it:

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
</head>
<body>

<input id="task" placeholder="New task">
<button id="add">Add</button>
<ul id="list"></ul>
<script>
  const input = document.getElementById("task");
  const list = document.getElementById("list");
  document.getElementById("add").addEventListener("click", () => {
    if (!input.value.trim()) return;
    const li = document.createElement("li");
    li.textContent = input.value;
    li.title = "Click to remove";
    li.addEventListener("click", () => li.remove());
    list.append(li);
    input.value = "";
    input.focus();
  });
</script>

</body>
</html>

Result