What is the DOM?
The Document Object Model is the browser's live representation of your HTML page. JavaScript can read and change it, which is how pages update without reloading.
Selecting elements
const title = document.getElementById("title");
const btn = document.querySelector(".btn"); // first match
const items = document.querySelectorAll("li"); // all matchesChanging content and style
title.textContent = "New title";
title.style.color = "crimson";
title.classList.add("highlight");
title.classList.toggle("hidden");
btn.setAttribute("disabled", "");Prefer textContent over innerHTML when inserting user text, to avoid injecting unwanted HTML.
Creating elements
const li = document.createElement("li");
li.textContent = "New task";
document.querySelector("ul").appendChild(li);Events
btn.addEventListener("click", () => {
console.log("Clicked!");
});
input.addEventListener("input", e => console.log(e.target.value));
form.addEventListener("submit", e => e.preventDefault());Common events: click, input, change, submit, keydown, mouseover and DOMContentLoaded.
Mini project: to-do list
<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", () => {
const text = input.value.trim();
if (!text) return;
const li = document.createElement("li");
li.textContent = text + " ";
const del = document.createElement("button");
del.textContent = "Delete";
del.onclick = () => li.remove();
li.appendChild(del);
list.appendChild(li);
input.value = "";
});
</script>Practice
Add a checkbox to each task that crosses out the text when ticked, and save the tasks in localStorage so they stay after reload.
Practice tasks
Reading is not enough. Try these without copying code, then compare with the lesson.
- Select an element with querySelector and change its text.
- Add a click listener that toggles a class.
- Build a counter button that updates the page.
Common mistakes
- Running DOM code before the elements exist.
- Adding a new listener every time instead of once.
Quick check
What does addEventListener do?
Runs a function when an event happens on an element.
What is the DOM?
The browser's object model of the page.