By the end of this lesson you will be able to explain what the DOM is, picture any web page as a tree, and use JavaScript to read facts about the page you are on. The next lessons build on this: first finding elements, then changing them, then reacting to the user.
HTML is text, the DOM is objects
Your HTML file is just text. When a browser loads it, the browser does not keep that text around and search through it every time something changes. Instead it parses the text and builds a structure of objects in memory. That structure is the Document Object Model, or DOM.
Each tag becomes an object you can talk to from JavaScript. A <p> becomes a paragraph object with properties such as its text and its class names. A <ul> becomes a list object that knows which items it contains. The browser draws the page from the DOM, so when your script changes an object, the screen updates.
Two points are worth remembering from the start:
- The DOM is live. It reflects the page as it is right now, including changes made by scripts.
- The DOM is separate from your file. Changing it never edits the HTML on the server. Refresh the page and you get the original again.
The page is a tree
HTML tags nest inside each other, and the DOM keeps that nesting as a tree. Take this small page:
<body>
<h1>Shopping</h1>
<ul>
<li>Milk</li>
<li>Bread</li>
</ul>
</body>Here body has two children, h1 and ul. The ul has two children, both li. We describe relationships using family words: ul is the parent of each li, the two li elements are siblings, and body is an ancestor of everything inside it.
Every item in the tree is a node. There are several kinds:
- Element nodes for tags such as
h1andli. - Text nodes for the text inside elements. The word "Milk" is its own node, a child of the
li. - Comment nodes for HTML comments.
- The document node at the very top, which holds the
htmlelement.
Even the whitespace and line breaks between tags become text nodes. This surprises many beginners, and it is why there are two sets of navigation properties, which we meet below.
The document object
In a browser, JavaScript gets a global variable called document. It represents the whole page and is your entry point. From it you can reach the top elements directly:
document.title // the text of the <title> tag
document.documentElement // the <html> element
document.body // the <body> element
document.head // the <head> elementRun this example to see them. The script lives inside the page, so it can read the page it belongs to.
<h1>Shopping</h1>
<ul id="list">
<li>Milk</li>
<li>Bread</li>
</ul>
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
out.textContent =
"body tag: " + document.body.tagName + "\n" +
"children of body: " + document.body.children.length;
</script>The <pre> shows the tag name of the body and how many element children it has. The script sits after the HTML it uses; the previous lessons on script tags explain why order matters, and we return to it shortly.
Walking around the tree
Once you hold one element you can move to its neighbours. The properties below return elements only, skipping text and comments, which is usually what you want:
| Property | Gives you |
|---|---|
parentElement |
the parent element |
children |
a live collection of child elements |
firstElementChild, lastElementChild |
the first and last child element |
nextElementSibling, previousElementSibling |
the neighbours at the same level |
There are also childNodes, firstChild and nextSibling, which include text nodes and therefore whitespace. Prefer the "Element" versions until you have a reason not to.
<ul id="list">
<li>Milk</li>
<li id="second">Bread</li>
<li>Eggs</li>
</ul>
<pre id="out"></pre>
<script>
const second = document.getElementById("second");
const lines = [
"parent tag: " + second.parentElement.tagName,
"previous: " + second.previousElementSibling.textContent,
"next: " + second.nextElementSibling.textContent,
"siblings in total: " + second.parentElement.children.length
];
document.getElementById("out").textContent = lines.join("\n");
</script>Nothing here was changed; we only read. That is a good first habit: explore with the DOM before you modify it.
When does the DOM exist?
The browser builds the DOM while it reads your HTML from top to bottom. If a <script> runs before the elements it needs, those elements are not in the tree yet and your code will not find them. Two common fixes:
- Put the script at the end of the
<body>, as in the examples above. - Keep the script in
<head>but add thedeferattribute, which waits until the page has been parsed.
We use the first approach in the examples because they are self-contained.
Looking at the DOM yourself
Your browser's developer tools show the live DOM in the Elements panel. Right-click anything on a page, choose Inspect, and you will see the tree. If a script has added elements, they appear there even though they are not in the original source. Comparing "view source" with the Elements panel is a quick way to see the difference between the HTML file and the DOM. You can also try the examples in our HTML viewer.
Common mistakes
- Running the script before the element exists. The error is usually that something is
null. Move the script below the HTML or usedefer. - Thinking you edited the file. Changes to the DOM disappear on refresh. Saving them needs a server or storage, which later lessons cover.
- Using
childNodesand being surprised by extra items. Whitespace between tags is a text node. Usechildrenfor elements. - Confusing the DOM with the HTML source. Browsers also fix mistakes in your HTML, such as a missing closing tag, so the DOM can differ from what you wrote.
- Believing the DOM is part of JavaScript itself. It is an interface the browser provides. Node.js has no
documentunless you add a library.
Exercise
Add a fourth item to the list in the second example. Then change the script so it also prints the text of the lastElementChild of the list and how many children the list has. Predict the numbers before you run it. As a stretch, open the Elements panel in your browser on any website and find the <body> node.
Next: Selecting elements.
Key points
- The DOM is a live, object-based model of the page that the browser builds from your HTML.
- The page is a tree of nodes; elements, text and comments are all different kinds of node.
- The global document object is the entry point for reading and changing the page.
- Every element node has properties such as tagName, children, parentElement and textContent.
- Changing the DOM changes what the user sees, but it does not change your original HTML file.