What the browser gives: window and the DOM

A browser gives a page two things: a window, which is the global object of the page, and a document, which is the tree of elements inside it. Every method in this part belongs to one of those two objects: the window carries timers, storage and history, and the document finds, changes, creates and removes the elements. The API is the same one a test and a server-side renderer use, so none of it is tied to a visible window.

The tool that gives Node.js a page is jsdom: it parses HTML, builds the tree and hands back a window with a document, a location and storage. This lesson installs it, opens a page, walks the tree and shows why one function can run on a page in jsdom and on a page in a browser. Every program in this part builds its own page with new JSDOM(html, { url }), so nothing depends on a file, a real network address or a window that is actually open.

A page in a folder of its own

jsdom is a library and not a program, so it is installed once per folder. The folder of this lesson is dom-course; npm puts the parser and its dependencies into node_modules and pins the version for that folder. The runs on this page used jsdom 30.1.3, and the version is worth writing down: a serialised element can differ between two versions of the library that parse the same page.

Install with npm install jsdom, then run the program with node.

mkdir dom-course
cd dom-course
npm install jsdom

The first program opens a page and prints five facts about it. The address in the url option matters: without it the page lives at about:blank, where a relative link and localStorage do not work.

The file setup.js:

const { JSDOM } = require('jsdom'); const html = '<!doctype html><html><head><title>Notes</title></head><body><h1>Notes</h1></body></html>'; const dom = new JSDOM(html, { url: 'http://localhost/' }); const { window } = dom; const { document } = window; console.log('the title:', document.title); console.log('the address:', document.URL); console.log('the window knows its document:', window.document === document); console.log('the page has a body:', document.body !== null); console.log('the user agent names jsdom:', window.navigator.userAgent.includes('jsdom'));

node setup.js

the title: Notes
the address: http://localhost/
the window knows its document: true
the page has a body: true
the user agent names jsdom: true

The title came from the title element and the address from the option, and the document is the same object the window holds. The last line is the proof that no browser is involved: the user agent string of the page names the library that parsed it. Everything else in this part is built on those two objects.

The window and the document

The window is the global object of a page: in a browser a variable created at the top of a script is a property of it, and window.window points back at the same object. The document is one property of the window, and the timers, the storage, the history and the location are others. A page therefore has no process, no require and no file system: those belong to the program that runs the page.

The program prints the parts of the window that this part of the course goes on to use, and the parts of the address that a page can read.

The file window.js:

const { JSDOM } = require('jsdom'); const dom = new JSDOM('<!doctype html><title>Notes</title><p>a page</p>', { url: 'http://localhost/notes', }); const { window } = dom; console.log('window is the global object of the page:', window.window === window); console.log('the node name of the document:', window.document.nodeName); console.log('timer functions:', typeof window.setTimeout, typeof window.clearTimeout); console.log('storage and history:', typeof window.localStorage, typeof window.history); console.log('the address:', window.location.href); console.log('the path:', window.location.pathname); console.log('the protocol and the host:', window.location.protocol, window.location.host);

node window.js

window is the global object of the page: true
the node name of the document: #document
timer functions: function function
storage and history: object object
the address: http://localhost/notes
the path: /notes
the protocol and the host: http: localhost

The document is a node like every other, which is why its name starts with a hash and it has no tag. The address is split into the pieces a program uses: the protocol decides whether storage is allowed, the host is the origin of a request, and the path is what a server has to answer. The page itself never prints the address bar, because a page has none.

The tree

A document is a tree of nodes. An element has children, and children counts only the elements among them, while childNodes also counts the text between the tags. The walk below is a function that calls itself for each element, which is the shape every program in this part uses when it has to look at the whole page.

The program prints the names with two spaces of indentation per level, counts the elements and reads the text of the body. The last lines ask the same tree for JSON, once for the body and once for the window, which is the mistake to avoid on a page.

The file tree.js:

const { JSDOM } = require('jsdom'); const html = [ '<!doctype html>', '<html>', '<head><title>Notes</title></head>', '<body>', '<h1>Notes</h1>', '<p>first <b>bold</b> word</p>', '<ul><li>one</li><li>two</li></ul>', '</body>', '</html>', ].join(''); const dom = new JSDOM(html, { url: 'http://localhost/' }); const { document } = dom.window; function walk(node, depth) { for (const child of node.children) { console.log(' '.repeat(depth) + child.tagName.toLowerCase()); walk(child, depth + 1); } } walk(document, 0); console.log('elements in the page:', document.getElementsByTagName('*').length); console.log('text in the body:', document.body.textContent); console.log('the body as JSON:', JSON.stringify(document.body)); try { JSON.stringify(dom.window); } catch (error) { console.log('the error:', error.name, '-', error.message.split('\n')[0]); }

node tree.js

html
  head
    title
  body
    h1
    p
      b
    ul
      li
      li
elements in the page: 10
text in the body: Notesfirst bold wordonetwo
the body as JSON: {}
the error: TypeError - Converting circular structure to JSON

Ten elements, and the text of the body runs the words together because the whitespace between the tags of the fixture is not text a page shows. The two JSON lines are the reason a lesson about a page prints text. An element keeps its data in internal slots and not in its own keys, so a writer sees an empty object and says nothing about the page. The window does have its own properties, and they point back at the window, so the writer follows a circle and stops with an error. A page prints textContent, a tag name, a count or a boolean, and never an object from the tree, which is also what keeps the output of these lessons the same on every run.

The same code in both places

A function that takes a document as its argument runs on any page, and a function that reads a global document runs only where that global exists. The separation is the whole difference between code that a test can call and code that needs a browser window. In this part every program passes the document in, which is why one file works in jsdom and in a browser unchanged.

The program defines one such function, calls it on two different pages and prints what the page has and what the program has.

The file both.js:

const { JSDOM } = require('jsdom'); const html = '<!doctype html><body><h1>Notes</h1><p>a short page</p></body>'; function summarise(document) { const heading = document.querySelector('h1'); const paragraphs = document.querySelectorAll('p').length; return `${heading.textContent}: ${paragraphs} paragraph(s)`; } const dom = new JSDOM(html, { url: 'http://localhost/' }); const second = new JSDOM(html, { url: 'http://localhost/' }); console.log('on the first page:', summarise(dom.window.document)); console.log('on the second page:', summarise(second.window.document)); console.log('the page has a window:', typeof dom.window); console.log('the page has no process of Node:', typeof dom.window.process); console.log('the program has the process of Node:', typeof process);

node both.js

on the first page: Notes: 1 paragraph(s)
on the second page: Notes: 1 paragraph(s)
the page has a window: object
the page has no process of Node: undefined
the program has the process of Node: object

One function, two pages, the same answer, and the last two lines are the border between the two worlds. A program that keeps its DOM work in functions like this one can be tested without a browser, and the same functions can be loaded into a page with a script tag when the time comes to run them for a reader.

Exercises

  1. Count the text nodes of the tree program with childNodes. Why is the number larger than ten?
  2. Open the same HTML with a url of http://localhost/shop and print location.host and location.pathname.
  3. Add a script that sets a value to the HTML of setup.js. Does jsdom run it without the runScripts option, and what does that tell you about the default?
  4. Print document.documentElement.tagName and document.doctype.name. What does a page have that an element does not?
  5. Call summarise of the last program on a page without an h1. What breaks, and which line of the function would you guard?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does jsdom give a Node.js program?

    Answer

    A window with a document, built from HTML

    jsdom parses the HTML and provides the browser objects in memory; nothing is drawn and no browser is installed.

  2. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<p>one</p>", { url: "http://localhost/" }); console.log(dom.window.document.querySelector("p").textContent);

    Answer

    one

    The parser built a paragraph, and the text of the element is the word it contains.

  3. Which object is the global object of a page?

    Answer

    window

    A global variable of a page is a property of the window, and the document is one property of that window.

  4. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<h1>Notes</h1><p>a page</p>", { url: "http://localhost/" }); console.log(dom.window.document.body.children.length);

    Answer

    2

    children counts elements, and the heading and the paragraph are the two of them.

  5. Why does JSON.stringify of the window throw?

    Answer

    Its own properties point back at the window, so the structure is circular

    The window has an own property that closes the circle back to itself, so a page prints text and numbers instead.

  6. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<p>a page</p>", { url: "http://localhost/notes" }); console.log(dom.window.location.pathname);

    Answer

    /notes

    The path is the part of the address after the host, and the url option is what put it there.

  7. What does the page have that the program does not?

    Answer

    A document and a location

    The window carries the page objects; process, require and the file system belong to Node.js.

  8. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<b>bold</b>", { url: "http://localhost/" }); console.log(typeof dom.window.document.body.firstElementChild);

    Answer

    object

    An element is an object, whatever it prints as, and the first child of the body is the bold one.

  9. Why is the url option passed to JSDOM?

    Answer

    It gives the page an origin, so location and relative links work

    Without it the page sits at about:blank, where storage and relative addresses have no origin.

  10. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<div id=box></div>", { url: "http://localhost/" }); console.log(dom.window.document.getElementById("box").tagName);

    Answer

    DIV

    A tag name from the DOM is uppercase, while the one printed by the tree walk was lowercased for the reader.

The programs on this page were run with Node.js 24.22.1 against jsdom 30.1.3 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev