DOM and events
The DOM is the browser's live tree of objects built from your HTML; change a node from JavaScript and the screen updates. Events (click, keypress, submit) travel through that tree in phases, and understanding bubbling is what makes event delegation work for elements added later.
18.1 What is the DOM?
- DOM = Document Object Model: a tree of objects the browser builds in memory from HTML.
- Every tag is a node: body inside html, the heading and list inside body.
- JavaScript changes these objects and the browser updates the screen.
- Step 1
1.Browser reads the HTML file
- Step 2
2.Builds the DOM tree (html -> body -> h1, ul#cart)
- Step 3
3.JavaScript selects a node and changes it
- Step 4
4.Browser recalculates layout if needed and repaints
- Step 5
5.User sees the updated page
18.2 Select, update and create elements
- querySelector(css) returns the first match; querySelectorAll returns all matches.
- textContent sets text; classList.add / remove / toggle manages CSS classes.
- createElement builds a node in memory only; append puts it on the screen.
- element.remove() deletes an element.
const title = document.querySelector("h1");const list = document.querySelector("#cart"); title.textContent = "Cart (2 items)";title.classList.add("active"); const item = document.createElement("li");item.textContent = "Headphones ₹1999";list.append(item);Page:# Cart (2 items)Shoes ₹2499Headphones ₹199918.3 Events and bubbling
- addEventListener("click", handler) runs the handler on every click.
- The handler gets an event object; event.target is the element actually clicked.
- After the button handles the click, the event travels up to its parents: event bubbling.
- So a click on Buy now also triggers the card's click listener.
const card = document.querySelector(".card");const btn = document.querySelector(".buy"); btn.addEventListener("click", (event) => { console.log("Button clicked");}); card.addEventListener("click", () => { console.log("Card clicked");});Console: Button clicked, Card clicked- Step 1
1.Capturing: window -> document -> ... -> parent (top down)
- Step 2
2.Target: the clicked element's listeners run
- Step 3
3.Bubbling: target -> parent -> ... -> window (bottom up)
- Step 4
4.Default listeners run in the bubbling phase; { capture: true } runs in capturing
- Step 5
5.stopPropagation() stops the travel; preventDefault() stops the browser's default action
| Method | What it stops | Example |
|---|---|---|
| event.stopPropagation() | The event travelling to other elements | Click on button should not open the card |
| event.preventDefault() | The browser's default action | Form submit reloading the page, link navigation |
18.4 Checkpoint: capture runs first
const card = document.querySelector(".card");const btn = document.querySelector(".buy"); btn.addEventListener("click", () => { console.log("Button");}); card.addEventListener("click", () => { console.log("Card");}, { capture: true }); btn.click();CardButton- The card's listener uses capture: true, so it runs in the capturing phase, before the target.
18.5 Bug: the new item's Remove button does nothing
- querySelectorAll + forEach attaches listeners only to buttons that exist at that moment.
- Watch was added later by addItem, so its button has no listener.
- Remove on Shoes works; Remove on Watch does nothing.
import { addItem } from "./cart-ui.js"; const list = document.querySelector("#cart");const buttons = list.querySelectorAll(".del"); buttons.forEach((btn) => { btn.addEventListener("click", () => { btn.closest("li").remove(); });}); addItem("Watch");Page after clicking Remove on Shoes and on Watch:# CartBag · RemoveWatch · Remove18.6 Fix: event delegation
- Attach one listener to the parent list instead of every button.
- Bubbling brings every button click up to the list anyway.
- event.target.closest(".del") finds the clicked Remove button; if none, return.
- Works for items added later, and uses less memory.
import { addItem } from "./cart-ui.js"; const list = document.querySelector("#cart"); list.addEventListener("click", (event) => { const btn = event.target.closest(".del"); if (!btn) return; btn.closest("li").remove();}); addItem("Watch");Page after clicking Remove on Shoes and on Watch:# CartBag · Remove- Step 1
1.User clicks Remove on Watch (added later)
- Step 2
2.Event bubbles from the button up to ul#cart
- Step 3
3.The single list listener runs
- Step 4
4.event.target.closest(".del") -> the Remove button (or null -> return)
- Step 5
5.btn.closest("li").remove() -> Watch removed
18.7 Loading scripts: normal vs async vs defer
| Type | Download | Runs | Order | Use for |
|---|---|---|---|---|
| <script> | Blocks HTML parsing | Immediately | In order | Rarely needed now |
| <script async> | Parallel | As soon as ready | Not guaranteed | Independent scripts like analytics |
| <script defer> | Parallel | After HTML is parsed | In order | Your app scripts |
| <script type="module"> | Parallel | After parse (deferred by default) | In order | Modern ES module code |
<!-- Wrong: TypeError: textContent of null --><head> <script src="app.js"></script></head> <!-- Right: runs after HTML parse --><head> <script src="app.js" defer></script></head><body> <h1>Cart</h1></body>18.8 Common mistakes
- A script in the head without defer: the body is not parsed yet, querySelector returns null.
- Putting user input into innerHTML: it is parsed as HTML and malicious code can run (XSS). Use textContent.
- Attaching listeners per item for dynamic lists instead of delegation.
- Updating the DOM again and again in a loop: each change can trigger layout. Build elements and append them together.
18.9 Interview tips
- DOM is a live tree of objects built from HTML; JS changes it and the browser repaints.
- Event phases: capturing, target, bubbling; listeners default to bubbling.
- Event delegation: one listener on a common parent, use event.target (closest) to find the real element; handles future elements.
- stopPropagation vs preventDefault: travel vs default action.
- textContent for user data (XSS safe); defer or type="module" for scripts.