So far JavaScript has run in isolation. Its real power on the web is manipulating the page live. The browser exposes the page to JavaScript as the DOM — the Document Object Model — a tree of objects you can read, change, add to and remove.
What is the DOM?
When the browser loads your HTML, it builds a live tree of objects — one per element. JavaScript reaches that tree through the global document. Change the tree and the page updates instantly.
Selecting elements
querySelector finds the first element matching any CSS selector; querySelectorAll finds them all:
const title = document.querySelector("#title"); // by idconst cards = document.querySelectorAll(".card"); // all matches (a NodeList)const firstButton = document.querySelector("button");
Reading & changing
const title = document.querySelector("#title");title.textContent = "Welcome back!"; // change text (safe)title.classList.add("is-active"); // add a CSS classtitle.classList.toggle("open"); // add/removetitle.style.color = "#2563eb"; // inline styletitle.setAttribute("data-id", "42"); // any attributeconst email = document.querySelector("#email");console.log(email.value); // read a form field
Events
An event is something that happens — a click, a keypress, a form submit. addEventListener runs a function when the event fires:
const button = document.querySelector("#enrol");button.addEventListener("click", () => {console.log("Enrol clicked!");});// The event object carries detailsconst form = document.querySelector("#lead");form.addEventListener("submit", (event) => {event.preventDefault(); // stop the page reloadingconst name = form.name.value;console.log("Submitted by", name);});
| Event | Fires when |
|---|---|
click | An element is clicked |
submit | A form is submitted |
input | A field value changes (per keystroke) |
keydown | A key is pressed |
DOMContentLoaded | The page HTML has finished parsing |
Creating elements
Build new nodes and add them to the tree — this is how lists and results render dynamically:
const list = document.querySelector("#tools");const tools = ["Excel", "SQL", "Python"];tools.forEach(tool => {const li = document.createElement("li");li.textContent = tool;list.appendChild(li);});
Practice
Build a tiny to-do input: a text field and a button. On click, read the field's value, create an <li> with that text, append it to a list, and clear the field. Bonus: also submit on Enter using a keydown listener.
Key takeaways
- 01The DOM is the live object tree of the page, reached through document.
- 02querySelector / querySelectorAll find elements using any CSS selector.
- 03Change text with textContent, classes with classList, and read fields with .value.
- 04Prefer textContent over innerHTML for user data to avoid XSS.
- 05addEventListener runs a function on events like click, submit and input; call preventDefault to stop default behaviour.
