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.