Course outline · 0% complete

0/30 lessons0%

Course overview →

Script tags and the DOM tree

lesson 8-1 · ~9 min · 24/30

Quiz

Warm-up from lesson 1-2: what does the browser build by parsing your HTML?

Getting JavaScript into the page

A page without JavaScript can only ever be a document. The DOM API is what turns it into an application, and every framework you will meet later (React, Vue) ultimately generates the same tree and the same calls you learn in this unit. The other reason this lesson matters: when your code "does nothing", the cause is usually here — the script ran at the wrong time.

<head>
  <script src="app.js" defer></script>
</head>
  • script src="app.js" loads and runs a JavaScript file.
  • defer says: download now, but run only after the HTML is fully parsed. Without it, a script in the head runs before the body exists, and code that touches elements finds nothing there.

You can also place the script tag at the end of body, or write code inline between <script> tags for quick tests. But src plus defer in the head is the habit worth building.

Once running, your code sees the page through one global object: document, the root of the DOM.

The DOM is a tree of objects

The browser turned your HTML nesting (boxes in boxes, lesson 2-2) into a tree: every element became a node object, nested elements became its children, and the wrapper is the parent. document sits at the root.

A tree of plain objects is something you can already handle:

const dom = {
  tag: "body",
  children: [
    { tag: "h1", children: [] },
    { tag: "ul", children: [
      { tag: "li", children: [] },
      { tag: "li", children: [] },
    ] },
  ],
};

Every DOM operation (find a node, change it, add children) is a walk through this structure. The real one just has richer nodes, with text content, classes, and styles attached.

documenthtmlheadbodyh1ullili
The DOM as a tree. The gold highlight visits nodes in depth-first order: parent first, then each child's whole subtree.

Code exercise · javascript

Run this walk of the toy DOM. It visits every node depth-first (the same order as the figure) and indents by depth, reconstructing the shape of the original HTML.

Code exercise · javascript

Your turn: write countTag(node, tag) that counts how many nodes in the tree (including the starting node) have the given tag. Same recursive shape as walk.