Switching the theme with a button
Make a "Dark theme" button that switches the page to a dark theme and back, while the button's text changes to "Light theme" and vice versa. The choice is remembered in localStorage.
The browser turns HTML into a tree of objects – the DOM. Through the DOM, JavaScript finds elements, changes text, style and classes, creates new elements and reacts to clicks and input. At the end of the lesson we build a small "To-do list" app that remembers its data even after the browser is closed.
document
└── html
├── head
│ └── title → "List"
└── body
├── h1 → "My tasks"
├── input#newTask
├── button#add
└── ul#list
├── li → "Learn the DOM"
└── li → "Do homework"
| Finding elements | Returns |
|---|---|
document.getElementById("list") | the element with id="list" |
document.querySelector(".card") | the first element that matches the CSS selector |
document.querySelectorAll("li") | all such elements (a list you can go through with for...of) |
<style>
.dark { background: #222; color: #eee; }
.box { padding: 12px; border-radius: 8px; transition: background 0.3s; }
</style>
<div id="k" class="box">
<h3 id="title">Title</h3>
<p>Click the buttons:</p>
<button id="b1">Change the text</button>
<button id="b2">Dark theme</button>
<button id="b3">Add an item</button>
<ul id="list"></ul>
</div>
<script>
const title = document.getElementById("title");
const box = document.getElementById("k");
const list = document.getElementById("list");
let n = 0;
document.getElementById("b1").addEventListener("click", () => {
title.textContent = "Text changed at " + new Date().toLocaleTimeString("en");
});
document.getElementById("b2").addEventListener("click", () => {
box.classList.toggle("dark"); // add the class if it is missing, remove it if it is there
});
document.getElementById("b3").addEventListener("click", () => {
n++;
const li = document.createElement("li"); // a new element
li.textContent = "Item " + n;
list.appendChild(li); // put it into the list
});
</script>
Result:
| Statement | What it does |
|---|---|
el.textContent = "..." | changes the element's text |
el.style.color = "red" | changes one CSS property (names with a hyphen are written joined: backgroundColor) |
el.classList.add / remove / toggle("name") | adds, removes, toggles a class – better than changing styles one by one |
document.createElement("li") + parent.appendChild(el) | creates and inserts a new element |
el.remove() | deletes the element |
input.value | the text typed into the field |
textContent, not with innerHTML. With innerHTML a typed <script> or <img onerror=...> would run – that is the XSS attack from the lesson Web application security.An event is something that happens on the page. A function that is called when the event happens is called an event listener:
element.addEventListener("click", function (e) {
// e = data about the event (e.g. e.key for a key, e.target for the element)
});
| Event | When it happens |
|---|---|
click | a mouse click or a tap |
input | every change of the text in a field |
change | a change of choice (select, checkbox) |
submit | sending a form |
keydown | pressing a key (e.key = "Enter", "ArrowUp"…) |
mouseover / mouseout | the mouse enters / leaves |
DOMContentLoaded | the HTML has loaded (defer can be used instead) |
<label>Type your name: <input id="name" type="text"></label>
<p id="greeting">Hello, ...!</p>
<label>Number: <input id="number" type="number" value="5"></label>
<p id="square"></p>
<script>
const nameField = document.getElementById("name");
nameField.addEventListener("input", () => {
document.getElementById("greeting").textContent = "Hello, " + (nameField.value || "...") + "!";
});
const number = document.getElementById("number");
function calculate() {
const x = Number(number.value); // text from the field -> number
document.getElementById("square").textContent = `${x}² = ${x * x}`;
}
number.addEventListener("input", calculate);
calculate(); // calculate right away at the start
</script>
Result:
<form id="f">
<label>Side a: <input name="a" type="number" required></label>
<label>Side b: <input name="b" type="number" required></label>
<button>Calculate</button>
</form>
<p id="res"></p>
<script>
document.getElementById("f").addEventListener("submit", e => {
e.preventDefault(); // do NOT send the form to the server and do not reload the page
const a = Number(e.target.a.value);
const b = Number(e.target.b.value);
if (a <= 0 || b <= 0) {
document.getElementById("res").textContent = "The sides must be positive.";
return;
}
document.getElementById("res").textContent = `Perimeter: ${2 * (a + b)}, area: ${a * b}`;
});
</script>
Result:
e.preventDefault() stops the default behaviour (sending the form and reloading the page) – that way JavaScript handles the data itself.
<style>
body { font-family: system-ui, Arial, sans-serif; }
.entry { display: flex; gap: 6px; }
.entry input { flex: 1; padding: 6px; }
ul { padding: 0; list-style: none; }
li { display: flex; align-items: center; gap: 8px; padding: 6px; border-bottom: 1px solid #ddd; }
li span { flex: 1; cursor: pointer; }
li.done span { text-decoration: line-through; color: #999; }
li button { border: 0; background: none; cursor: pointer; font-size: 1.1rem; }
</style>
<h3>My tasks</h3>
<form class="entry" id="form">
<input id="newTask" placeholder="New task..." autocomplete="off">
<button>Add</button>
</form>
<ul id="list"></ul>
<p id="counter"></p>
<script>
// data: an array of objects { text, done }
let tasks = [];
try { tasks = JSON.parse(localStorage.getItem("tasks")) || []; } catch (e) {}
function save() {
try { localStorage.setItem("tasks", JSON.stringify(tasks)); } catch (e) {}
}
function render() {
const list = document.getElementById("list");
list.innerHTML = ""; // clear the old list (no user text here)
tasks.forEach((t, i) => {
const li = document.createElement("li");
if (t.done) li.classList.add("done");
const text = document.createElement("span");
text.textContent = t.text; // textContent – safe
text.addEventListener("click", () => { t.done = !t.done; save(); render(); });
const del = document.createElement("button");
del.textContent = "✕";
del.title = "Delete";
del.addEventListener("click", () => { tasks.splice(i, 1); save(); render(); });
li.append(text, del);
list.appendChild(li);
});
const left = tasks.filter(t => !t.done).length;
document.getElementById("counter").textContent = `Remaining: ${left} of ${tasks.length}`;
}
document.getElementById("form").addEventListener("submit", e => {
e.preventDefault();
const field = document.getElementById("newTask");
const text = field.value.trim();
if (text === "") return;
tasks.push({ text: text, done: false });
field.value = "";
save();
render();
});
render();
</script>
Result:
Key ideas:
tasks; after every change the function render() draws the list again from the array;JSON.stringify, and back with JSON.parse (the same JSON as in the lesson API and JSON);This app is the same idea as the To-do app in Flask (SR), except that there the server keeps the data.
Each task has an example, a hint and a solution. The solutions have been checked in the browser.
Make a "Dark theme" button that switches the page to a dark theme and back, while the button's text changes to "Light theme" and vice versa. The choice is remembered in localStorage.
The computer picks a number from 1 to 100. The user types a guess into a field and clicks "Check"; below it the page shows "Higher", "Lower" or "Correct in N tries!". A "New game" button picks a new number.
null – put the <script> at the end of body or use defer.Number().e.preventDefault(), otherwise the page reloads.textContent, not with innerHTML.1. What does document.querySelector(".card") return?
2. How do you safely put text typed by the user into an element?
3. What is e.preventDefault() for in a submit event?
4. Where does localStorage keep data?