DevPath · Learn to code ESPTEN

The DOM and Events

What is the DOM?

The DOM (Document Object Model)

When the browser loads an HTML page, it does not just keep the text: it builds in memory a structure of objects that represents every tag, attribute and text. That structure is the DOM (Document Object Model).

The DOM is a tree: the document contains <html>, which contains <head> and <body>, which in turn contain other elements. Each node of the tree is an object with properties and methods that JavaScript can read and modify.

<body>
  <h1>Hello</h1>
  <p>Welcome</p>
</body>

That HTML produces a tree like this:

document
 └─ html
     └─ body
         ├─ h1  → "Hello"
         └─ p   → "Welcome"

The document object

The entry point to the DOM is the global variable document. From it you can search for elements, create them or modify them:

console.log(document.title); // title of the tab

Note about this practice environment: the editor includes a practice document (a reduced version of the real one) with an empty document.body. It supports the essentials — createElement, textContent, classList, setAttribute, appendChild, querySelector/querySelectorAll (selectors #id, .class, tag), getElementById, addEventListener and click() — so in the exercises you will manipulate the DOM for real, not just strings.

Examples

Traverse the DOM (illustrative browser example)

// In a real browser this would read the page.
// Here we only show it as an illustration of the concept:
const html = "<ul><li>one</li><li>two</li></ul>";
console.log("Structure as text:", html);
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Select and modify elements →