Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 156 ยท The DOM

The DOM

Understand the DOM from JavaScript's side - node types, elements vs text nodes, the document and window objects, element interfaces and when scripts can run.

Everything you have learned so far โ€” variables, functions, objects, arrays, async code โ€” works the same in any JavaScript runtime. This chapter is where JavaScript meets the browser. When a page loads, the browser turns its HTML into a tree of objects called the Document Object Model, or DOM, and hands your scripts a reference to it. Read those objects and you learn what is on the page; change them and the page on screen changes too.

If you took the HTML course, you already met the DOM briefly in The Document Object Model: querySelector(), textContent, createElement() and classList. This chapter goes deeper. In this first lesson you will look at the DOM as a JavaScript programmer: what kinds of objects live in the tree, how they relate to each other, what document and window are, and why the timing of your script matters.

The DOM is a tree of objects

The browser parses your HTML into a tree. Every tag becomes an element object, every run of text becomes a text node, and the whole thing hangs from one root object: document. All these objects share a common base type called Node, which is why "node" is the general word for anything in the tree.

Each node knows its place. It has a parent (except document), it may have children, and it may have siblings. You will learn to walk these links in Traversing the DOM; for now, the important idea is that the tree you see in DevTools is made of real JavaScript objects that you can inspect like any other object.

The quickest way to see the tree is to write a small recursive function that walks it. The example below uses childNodes (every child, including text) and the nodeType property, which tells you what kind of node you are holding.

Printing the DOM tree

Look closely at the output. Between the tags there are text nodes containing only a line break and spaces, such as "\n ". They come from the indentation in your HTML. The DOM keeps them because whitespace can matter in text, so any code that looks at all child nodes has to expect them. The comment is a node too.

Node types

nodeType is a number, and the Node object has named constants for each value, so you never need to memorize the numbers:

Constant Value Example
Node.ELEMENT_NODE 1 <p>, <button>, <svg>
Node.TEXT_NODE 3 The words inside a <p>
Node.COMMENT_NODE 8 <!-- a comment -->
Node.DOCUMENT_NODE 9 document itself
Node.DOCUMENT_FRAGMENT_NODE 11 A fragment or a template's content

In everyday code you mostly care about elements. Most DOM methods you will use โ€” querySelector(), children, closest(), classList โ€” deal only with elements and skip text and comments entirely. The node-level properties like childNodes and firstChild are there when you need every detail, for example when highlighting words inside text.

A few other properties help you identify a node:

  • nodeName โ€” "P" for elements in an HTML document (uppercase), "#text" for text, "#comment" for comments.
  • tagName โ€” the same as nodeName, but exists only on elements.
  • localName โ€” the lowercase tag name, handy for comparisons.
  • data / nodeValue โ€” the text inside a text or comment node.

Elements are objects with a family tree

A <button> in the DOM is not just "an element". It is an instance of a specific class, HTMLButtonElement, which inherits from a longer chain. Each step adds features:

  • EventTarget โ€” can receive events (addEventListener()).
  • Node โ€” has a place in the tree (parentNode, childNodes, appendChild()).
  • Element โ€” has attributes, classes and selectors (getAttribute(), classList, querySelector()).
  • HTMLElement โ€” common HTML features (hidden, title, dataset, click(), focus()).
  • HTMLButtonElement โ€” button-specific features (disabled, type, form).

This is the same prototype chain you studied with your own classes, so instanceof works exactly as you would expect.

An element's prototype chain

Knowing the specific class tells you which properties exist. An HTMLInputElement has value, checked and valueAsNumber; an HTMLAnchorElement has href, pathname and hostname; a <p> has none of those. When you are unsure what an element offers, logging element.constructor.name is a good first step.

The document object

document is the root of the tree and your entry point into it. Besides the search methods you will learn in the next lesson, it gives you shortcuts to the main parts of the page:

  • document.documentElement โ€” the <html> element.
  • document.head and document.body โ€” the <head> and <body> elements.
  • document.title โ€” the page title, which you can also set.
  • document.readyState โ€” "loading", "interactive" (HTML parsed) or "complete" (everything loaded).
  • document.activeElement โ€” the element that currently has keyboard focus.
  • document.forms, document.images, document.links โ€” live collections of those elements.

The window object

window represents the browser tab (or, in our editors, the preview frame). It plays two roles at once:

  1. It is the global object. Global functions and objects such as setTimeout, console, fetch, JSON, Math and document itself are properties of window. window.document === document is true. In any environment, globalThis refers to the same object, which is the portable way to write it.
  2. It describes the viewport and the tab. innerWidth and innerHeight give the viewport size, scrollY the scroll position, location the current URL and history the session history (covered in URLs, Location and History).
document and window

Notice that the last listener is attached with a bare addEventListener(...). Because window is the global object, that call is really window.addEventListener(...). Resize the preview pane to see it fire.

Don't rely on elements becoming globals. Browsers create a global variable for every element with an id, so <div id="cart"> appears as window.cart. It is a legacy feature: the variable is silently shadowed by any real variable with the same name, and it makes code hard to follow. Always look elements up explicitly.

The DOM is not your source code

The DOM starts from your HTML, but it is not the same thing:

  • The parser repairs HTML. A <table> written without <tbody> gets one anyway. A <p> that you never closed is closed for you. Missing <html>, <head> and <body> tags are created.
  • Scripts change it constantly. Once JavaScript adds, removes or edits nodes, the DOM no longer matches the file at all.
  • It holds state the HTML never had. What the user typed into an input lives in the DOM (input.value), not in the markup.

Three other common misunderstandings: the DOM is not part of the JavaScript language (it is an API the browser provides, which is why Node.js has no document); it is not only for JavaScript (the same tree is what CSS selectors match and what assistive technology reads); and it is not the same as the visible page, because hidden elements (display: none) are in the DOM even though nobody sees them.

This is why DevTools has two views of a page: View source shows the file the server sent, and the Elements panel shows the live DOM.

The parser fixes your markup

When can a script use the DOM?

The browser builds the DOM as it reads the HTML, top to bottom. A classic <script> runs the moment the parser reaches it, so it can only see elements that come before it. A script in the <head> that looks for a button in the <body> gets null.

You have three good options:

  • Use defer on external scripts: <script src="app.js" defer></script>. The file downloads in parallel and runs after the document is parsed, in order. This is the usual choice.
  • Use a module: <script type="module" src="app.js"></script>. Modules are deferred automatically (see Modules).
  • Wait for DOMContentLoaded, an event on document that fires once the HTML is fully parsed.
JavaScript
document.addEventListener("DOMContentLoaded", () => {
  // Every element in the HTML exists now.
  document.querySelector("#menu-toggle").hidden = false;
});

The examples in this course place the <script> at the end of the HTML, which also works, because the elements above it have already been parsed. The HTML side of this is explained in Adding JavaScript to HTML.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does node.nodeType === Node.TEXT_NODE check?

    Text nodes hold the actual characters of the page. Node.TEXT_NODE (value 3) identifies them; elements are Node.ELEMENT_NODE (1).
  2. 2. Why does childNodes of a nicely indented <ul> include more items than its <li> elements?

    The line breaks and spaces you use to indent HTML become whitespace-only text nodes, and childNodes includes every node type.
  3. 3. Which statement about window is true?

    In the browser, window is the global object (also available as globalThis). Globals like setTimeout, console and document are its properties.
  4. 4. A script in the <head> (no defer) runs document.querySelector("#save") for a button in the <body>. What does it get?

    A classic script runs as soon as the parser reaches it. The button doesn't exist yet. Use defer, a module or DOMContentLoaded.
  5. 5. Your HTML has a <table> with <tr> rows directly inside. What is the table's first element child in the DOM?

    The HTML parser wraps rows in a <tbody> automatically. The DOM reflects the repaired structure, not the exact source.

Summary

  • The DOM is a tree of JavaScript objects built from your HTML; everything in it is a node.
  • nodeType tells element, text, comment and document nodes apart. Most everyday APIs deal only with elements.
  • Each element is an instance of a specific class, such as HTMLButtonElement, which inherits from HTMLElement, Element, Node and EventTarget.
  • document is your entry point to the tree; window is the global object and describes the tab and viewport.
  • The DOM is repaired and changed by the browser and your scripts, so it often differs from the HTML source.
  • Scripts can only see elements that are already parsed: use defer, modules or DOMContentLoaded.

Next: Selecting Elements โ€” finding exactly the elements you need with selectors, collections, closest() and matches().