SkillPilotAI

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.
From HTML to the screen
  1. 1.Browser reads the HTML file

  2. 2.Builds the DOM tree (html -> body -> h1, ul#cart)

  3. 3.JavaScript selects a node and changes it

  4. 4.Browser recalculates layout if needed and repaints

  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.
JavaScript
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);
Output
Page:# Cart (2 items)Shoes ₹2499Headphones ₹1999

18.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.
JavaScript
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");});
Output
Console: Button clicked, Card clicked
The 3 phases of an event
  1. 1.Capturing: window -> document -> ... -> parent (top down)

  2. 2.Target: the clicked element's listeners run

  3. 3.Bubbling: target -> parent -> ... -> window (bottom up)

  4. 4.Default listeners run in the bubbling phase; { capture: true } runs in capturing

  5. 5.stopPropagation() stops the travel; preventDefault() stops the browser's default action

MethodWhat it stopsExample
event.stopPropagation()The event travelling to other elementsClick on button should not open the card
event.preventDefault()The browser's default actionForm submit reloading the page, link navigation

18.4 Checkpoint: capture runs first

JavaScript
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();
Output
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.
JavaScript
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");
Output
Page after clicking Remove on Shoes and on Watch:# CartBag · RemoveWatch · Remove

18.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.
JavaScript
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");
Output
Page after clicking Remove on Shoes and on Watch:# CartBag · Remove
Event delegation flow
  1. 1.User clicks Remove on Watch (added later)

  2. 2.Event bubbles from the button up to ul#cart

  3. 3.The single list listener runs

  4. 4.event.target.closest(".del") -> the Remove button (or null -> return)

  5. 5.btn.closest("li").remove() -> Watch removed

18.7 Loading scripts: normal vs async vs defer

TypeDownloadRunsOrderUse for
<script>Blocks HTML parsingImmediatelyIn orderRarely needed now
<script async>ParallelAs soon as readyNot guaranteedIndependent scripts like analytics
<script defer>ParallelAfter HTML is parsedIn orderYour app scripts
<script type="module">ParallelAfter parse (deferred by default)In orderModern ES module code
HTML
<!-- 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.