IntermediateLesson 12 of 16
DOM & Events in the Browser – JavaScript
Creating and changing elements and reacting to clicks.
The browser represents the page as a tree of objects – the DOM. With document.querySelector you find elements by CSS selector, and with createElement you create new ones. The examples here build their own elements so that they run anywhere.
const liste = document.createElement("ul");
for (const t of ["Milk", "Bread", "Eggs"]) {
const li = document.createElement("li");
li.textContent = t;
liste.append(li);
}
document.body.append(liste);
console.log(document.querySelectorAll("li").length); // 3
console.log(liste.children[1].textContent); // BreadYou attach events with addEventListener. Instead of giving every list item its own handler, you use event delegation: one handler on the parent element that uses event.target to determine which child was hit.
liste.addEventListener("click", (event) => {
const li = event.target.closest("li");
if (li) {
li.classList.toggle("erledigt");
console.log(li.textContent, li.classList.contains("erledigt"));
}
});
liste.children[1].click(); // triggers a click from code
liste.children[1].click();On a real page you usually access existing elements. With ?. the code stays safe if the element is missing:
const knopf = document.querySelector("#knopf"); // <button id="knopf">
knopf?.addEventListener("click", () => {
document.querySelector("#titel")?.classList.add("aktiv");
});
const box = document.createElement("div");
box.dataset.id = "42"; // data-id="42"
box.style.color = "crimson";
console.log(box.outerHTML);WarningNever insert third-party or user-entered text with
innerHTML – this opens the door to script injection (XSS). Use textContent or create elements with createElement.TipFrameworks like React, Vue or Svelte take manual DOM handling off your hands. If you understand the DOM, you also understand what they do behind the scenes.