Thuta Learning
JavaScript
IntermediateProgrammingBeginner

JS DOM Intro

JavaScriptLesson 2420 min

What you'll walk away with

  • Draw a piece of HTML as a DOM tree of element and text nodes
  • Find an element from the document object and change its textContent
  • Move around the tree with parentNode, childNodes and children
  • Fix the null you get when a script runs before its element exists, using defer or DOMContentLoaded

Explain it simply

Explain it simply

An HTML file is like the blueprint of a house. The browser reads the blueprint and builds the actual house, and that house is the DOM (Document Object Model). JavaScript never edits the blueprint; it walks into the finished house and repaints walls or moves furniture.

The DOM is shaped like a tree. document sits at the top, html below it, then head and body, and the page's elements below body. Every tag becomes an element node and the text inside tags becomes text nodes. JavaScript handles those nodes as ordinary objects.

Problem → Why → Solution

The problem: null for an element that is clearly there

This is the first DOM error most beginners meet. The HTML plainly contains <p id="greeting">, yet opening the page prints a TypeError in the console: "Cannot set properties of null (setting 'textContent')". Moving the script to the bottom of the body makes it work, and nobody quite knows why.

index.html
<!doctype html>
<html>
  <head>
    <script>
      // Runs immediately: the <body> has not been parsed yet
      const greeting = document.getElementById("greeting"); // null
      greeting.textContent = "Hello from the DOM!";         // TypeError
    </script>
  </head>
  <body>
    <p id="greeting">Loading...</p>
  </body>
</html>

Why is it null?

The browser builds the DOM gradually while it reads the HTML from top to bottom. When it meets a plain <script> tag it pauses parsing and runs the script immediately. At that moment the <p> has not been read, so it does not exist in the DOM yet and getElementById returns null. The script needs to run after the DOM is built, which is what defer is for.

Core concept: the DOM is a live node tree built from HTML

The browser parses the HTML text and builds a tree of objects in memory. The root of that tree is the document object, and every piece of DOM work in JavaScript starts there: document.body, document.getElementById() and so on. Each node is linked to its relatives through parentNode, childNodes and nextSibling, so you can move up, down and sideways through the tree.

Node kindnodeTypeExample
Element1 (Node.ELEMENT_NODE)<p>, <section>, <button>
Text3 (Node.TEXT_NODE)The "Hello" inside a <p>
Comment8 (Node.COMMENT_NODE)<!-- note -->
Document9 (Node.DOCUMENT_NODE)document itself

Every node is a real JavaScript object with properties and methods. An element node knows its nodeName (always upper case for HTML elements, such as "SECTION"), its id and className, and its text through textContent. Reading those properties is harmless; assigning to them changes what the user sees. The next lessons cover finding elements, changing them and reacting to events, one at a time.

The DOM is not always identical to the HTML file. The browser fills in tags you forgot to close, and the changes JavaScript makes live only in the DOM; they never travel back into the file. That is why View Source shows the original HTML while the Elements panel in DevTools shows the current DOM. Refresh the page and every JavaScript change disappears as the DOM is rebuilt from the HTML.

Keep in mind that the DOM is not part of the JavaScript language; it is a Web API the browser provides. Node.js has no document object, so running DOM code there fails with "document is not defined". Finally, a DOM change can make the browser recalculate styles, redo layout and repaint, so grouping many changes together is faster than scattering them.

Mental model: HTML in, tree out, JS edits the tree
  1. Browser reads HTML top to bottom
  2. Tags and text become nodes
  3. JS finds nodes starting at document
  4. Changed nodes are redrawn on screen

JavaScript edits the in-memory tree, never the HTML file, and a refresh rebuilds the tree from the HTML.

General pattern

javascript
const element = document.getElementById("some-id"); // element or null
element.textContent = "new text";                      // change the page

element.parentNode;        // one level up
element.children;          // child elements only
element.childNodes;        // children including text nodes

document.addEventListener("DOMContentLoaded", () => {
  // the whole HTML has been parsed: every element exists
});

Every DOM task starts at document, finds an element, then reads or changes that node's properties. children returns elements only, while childNodes also includes whitespace text nodes. If the script might run before the element exists, wait for DOMContentLoaded.

Example: looking inside a profile card's DOM tree

This code builds the elements it needs, so you can paste it into the DevTools console of a blank page such as about:blank. It creates a profile card, prints its tree with indentation using printTree(), and then changes one text node.

dom-tree.js
// Run in a browser: paste into the DevTools console of a blank page.
const card = document.createElement("section");
card.id = "profile";
card.innerHTML = "<h2>Aung Kyaw</h2><p>Web developer</p>";
document.body.append(card);

function printTree(node, depth = 0) {
  const indent = "  ".repeat(depth);
  if (node.nodeType === Node.TEXT_NODE) {
    console.log(`${indent}#text "${node.textContent}"`);
    return;
  }
  console.log(indent + node.nodeName);
  for (const child of node.childNodes) printTree(child, depth + 1);
}

printTree(card);
console.log(card.parentNode === document.body);
document.querySelector("#profile p").textContent = "Senior web developer";
console.log(card.lastChild.textContent);

Code breakdown

  1. Create and attachdocument.body.append(card);

    createElement() only builds the node in memory. It becomes part of the document tree, and appears on screen, once append() puts it inside body.

  2. Text nodes are nodes tooif (node.nodeType === Node.TEXT_NODE) {

    nodeType tells node kinds apart. The text "Aung Kyaw" is not a property of the h2; it is a separate text node that is the h2's child.

  3. Walk the childrenfor (const child of node.childNodes) printTree(child, depth + 1);

    printTree() calls itself for every child in childNodes with one more level of indentation, which visits the tree from the top down to the leaves.

  4. Parent linkconsole.log(card.parentNode === document.body);

    After append(), card's parentNode is body, so this prints true. It is the link that lets you climb back up the tree.

  5. Change the treedocument.querySelector("#profile p").textContent = "Senior web developer";

    Assigning textContent replaces the p's text node and the page updates at once. card.lastChild is that same p, so it shows the new text.

You should see
SECTION
  H2
    #text "Aung Kyaw"
  P
    #text "Web developer"
true
Senior web developer

Where and when your script should run

On modern projects the simplest fix is putting <script src="app.js" defer></script> in the head. A deferred script downloads while the HTML is parsed and runs after the whole document has been parsed, just before DOMContentLoaded. Scripts with type="module" are deferred by default. Inline scripts need to wait for the DOMContentLoaded event instead.

index.html
<head>
  <!-- runs after parsing finishes, so #greeting exists -->
  <script src="app.js" defer></script>
</head>

Do not confuse DOMContentLoaded with the load event. DOMContentLoaded fires once the HTML is parsed and deferred scripts have run. load fires later, after images, stylesheets and other resources have finished downloading. For DOM setup DOMContentLoaded is enough; waiting for load slows the page down for no reason.

In real projects

Where this shows up in real projects

Even with frameworks like React, Vue or Svelte, everything on screen is ultimately DOM nodes; the framework simply updates the DOM for you. When hunting a UI bug, the fastest move is to inspect the element in the DevTools Elements panel and see which classes, attributes and text it really has. In the console, $0 refers to the element selected in the Elements panel, so you can experiment on it right away.

Before building a feature, it helps to sketch a component such as a profile card as a DOM tree on paper and mark which text nodes, classes and attributes change when a button is clicked. In tests, Jest or Vitest run with a jsdom environment that provides a simulated DOM inside Node.js, so DOM code can be tested without opening a browser.

Common mistakes

Common mistakes

1. Running the script before the element exists

A script in the head without defer runs before the body is parsed, so every selector returns null. Add defer, use type="module", or wait for DOMContentLoaded.

2. Expecting childNodes to contain only elements

When HTML is indented, the line breaks and spaces between tags become whitespace text nodes, so ul.childNodes[0] may be a text node rather than the first li. Use children and firstElementChild when you only want elements.

3. Running DOM code in Node.js

node app.js fails with "ReferenceError: document is not defined" because the browser, not JavaScript itself, supplies document. Run DOM code in a browser, or use a DOM simulation such as jsdom for tests.

Best practices

Best practices

  • Load external scripts in the head with defer so the HTML and the script download in parallel.
  • When unsure how to change the DOM, inspect it in the Elements panel first and experiment on $0 in the console.
  • When adding many elements, build them first and append them in one go rather than one by one.

Mini challenge

Mini challenge: climb and count the tree

Write pathTo(), which lists the chain of parents from an element up to html, and countNodes(), which counts the element nodes and text nodes in a subtree. Your solution must build the elements it needs itself.

  • Build <div><article><p>Read <strong>this</strong> first</p></article></div> and add it to body
  • pathTo(strong) returns "HTML > BODY > DIV > ARTICLE > P > STRONG" (use parentElement)
  • countNodes(div) finds 4 elements and 3 text nodes
  • Use recursion over childNodes
tree-walk.js
// TODO: create the div, set its HTML, append it to document.body

function pathTo(element) {
  // TODO: collect nodeName values while walking up parentElement
  // TODO: return them joined with " > ", starting from HTML
}

function countNodes(node) {
  // TODO: count this node (Node.ELEMENT_NODE or Node.TEXT_NODE)
  // TODO: add the counts of every child in node.childNodes
  return { elements: 0, texts: 0 };
}

// TODO: print pathTo(the strong element) and the counts for the div

Expected: The console shows: HTML > BODY > DIV > ARTICLE > P > STRONG Elements: 4, text nodes: 3

Show hint

The html element's parentElement is null, so a while (current !== null) loop stops there. Adding names with unshift() puts HTML first by the time you call join().

Show solution
tree-walk.js
// Builds its own elements, so it works on any blank page.
const box = document.createElement("div");
box.innerHTML = "<article><p>Read <strong>this</strong> first</p></article>";
document.body.append(box);

function pathTo(element) {
  const names = [];
  let current = element;
  while (current !== null) {
    names.unshift(current.nodeName);
    current = current.parentElement;
  }
  return names.join(" > ");
}

function countNodes(node) {
  const counts = { elements: 0, texts: 0 };
  if (node.nodeType === Node.ELEMENT_NODE) counts.elements += 1;
  if (node.nodeType === Node.TEXT_NODE) counts.texts += 1;
  for (const child of node.childNodes) {
    const inner = countNodes(child);
    counts.elements += inner.elements;
    counts.texts += inner.texts;
  }
  return counts;
}

const strong = box.querySelector("strong");
console.log(pathTo(strong));
const { elements, texts } = countNodes(box);
console.log(`Elements: ${elements}, text nodes: ${texts}`);

Quick quiz 1 / 3

For <p>Hi <b>there</b></p>, what is the p element's childNodes.length?

Quick quiz 2 / 3

An inline <script> in the head, without defer, calls document.getElementById("app") for a <div id="app"> in the body. What does it get?

Quick quiz 3 / 3

What happens when you run console.log(document.title) in Node.js?

What to remember

  • The DOM is the node tree a browser builds from HTML, with document at the root.
  • Tags become element nodes and text becomes text nodes; move around with parentNode, children and childNodes.
  • JavaScript changes the in-memory DOM, not the HTML file, and a refresh rebuilds it.
  • A script that runs before its element exists gets null; use defer, type="module" or DOMContentLoaded.

MDN — Document Object Model (DOM) — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

JS DOM Intro | Thuta Learning