Skip to main content

The DOM and Events

The Document Object Model (DOM) is the tree of objects the browser builds from your HTML. JavaScript reads and changes it.

Selecting and changing elements​

const title = document.querySelector("#title");
const items = document.querySelectorAll(".item");

title.textContent = "Updated title";
title.classList.add("highlight");
title.setAttribute("data-state", "ready");

const li = document.createElement("li");
li.textContent = "New item";
document.querySelector("ul").append(li);
CAUTION

Use textContent for user-provided text. Assigning untrusted input to innerHTML can cause cross-site scripting (XSS).

Events​

const button = document.querySelector("#save");

button.addEventListener("click", (event) => {
event.preventDefault();
console.log("clicked", event.target);
});

Common events: click, input, change, submit, keydown, scroll, DOMContentLoaded.

Event delegation​

Attach one listener to a parent instead of one per child. Events bubble up the tree.

document.querySelector("ul").addEventListener("click", (e) => {
const li = e.target.closest("li");
if (li) li.classList.toggle("done");
});

A small interactive example​

<button id="inc">Clicked 0 times</button>
<script>
let n = 0;
const btn = document.getElementById("inc");
btn.addEventListener("click", () => {
n += 1;
btn.textContent = `Clicked ${n} times`;
});
</script>

Storage​

APILifetimeSize
localStorageUntil clearedAbout 5 MB
sessionStorageUntil the tab closesAbout 5 MB
CookiesConfigurable; sent with requestsAbout 4 KB