When the browser loads your HTML, it does not keep the text. It builds a model of the page in memory: a tree of objects. That model is the DOM, the Document Object Model. JavaScript works with the DOM, and the browser redraws the page whenever the DOM changes.
<body>
<h1>Title</h1>
<p>Hello <strong>world</strong></p>
</body>
The browser turns this into a tree:
document
└── html
├── head
└── body
├── h1 ("Title")
└── p
├── "Hello "
└── strong ("world")
Every box is a node. Elements (h1, p) are nodes, and so is the text inside them.
The document object
document is your entry point to the whole tree. Everything starts there.
<h1 id="title">Hello</h1>
<script>
console.log(document.title); // the text of <title>
console.log(document.body.children.length); // how many elements are in body
console.log(document.querySelector("#title").tagName); // → H1
</script>
The DOM is not the HTML file
The DOM is a live copy. If JavaScript changes it, the screen changes, but the original file does not. And the browser can fix HTML while building the DOM, for example by adding a missing <tbody>.
<p id="note">Original text</p>
<script>
document.querySelector("#note").textContent = "Changed by JavaScript";
</script>
The DOM is not JavaScript
The DOM is part of the Web APIs that browsers provide. JavaScript is the language you use to work with it. Other languages can use the DOM too. See Web APIs vs the JavaScript Language.
The usual workflow
- Select an element:
document.querySelector("..."). - Change it: text, attributes, classes or styles.
- Create or remove elements when needed.
- React to events: clicks, typing and so on.
The lessons in this chapter take these steps one by one, and the next chapter covers events.
Elements vs nodes
children lists only elements. childNodes lists all nodes, including text and comments. Most of the time you want the element versions: children, firstElementChild, nextElementSibling.