JavaScript Tutorial · Chapter 6 of 8
JS DOM Updates
Create and insert elements.
createElement builds a new node. appendChild inserts it into the page.
Validate input before adding items to a list.
DOM sample
Try it Yourself »
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DOM Updates</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>To-Do List</h1>
<div class="row">
<input id="taskInput" type="text" placeholder="Add a task">
<button id="addButton">Add</button>
</div>
<ul id="todoList"></ul>
<script src="script.js"></script>
</body>
</html>
style.css
body {
font-family: Arial, sans-serif;
padding: 32px;
background: #f8fafc;
}
.row {
display: flex;
gap: 8px;
margin-bottom: 16px;
}
input, button {
padding: 10px 12px;
border-radius: 8px;
border: 1px solid #cbd5e1;
}
button {
border: 0;
background: #0f766e;
color: white;
}
script.js
const input = document.getElementById("taskInput");
const list = document.getElementById("todoList");
document.getElementById("addButton").addEventListener("click", function () {
const text = input.value.trim();
if (!text) {
return;
}
const item = document.createElement("li");
item.textContent = text;
list.appendChild(item);
input.value = "";
input.focus();
});
Classroom Tips
- Trim input before checking emptiness.
- Clear the input after a successful add.