When a browser loads HTML it builds the DOM (Document Object Model): one JavaScript object for every element and piece of text, arranged as a tree.
document is the root object. document.body is the <body> element, and every tag inside it is a node in the tree.
An element's children are the elements directly inside it. Its parent is the element that contains it, and elements side by side are siblings.
Text inside a tag is a separate text node. Properties like children and firstElementChild skip text nodes; childNodes includes them.
Nodes have a nodeType: 1 for elements, 3 for text, 8 for comments. Element extends Node, so elements get extra APIs such as classList and querySelector.
Whitespace between tags becomes text nodes. That is why firstChild is often an empty-looking text node while firstElementChild is the tag you expect.
children is a live HTMLCollection that updates as the DOM changes; querySelectorAll (next lesson) returns a static NodeList snapshot.
The DOM is not the HTML source: the browser fixes invalid markup, and scripts change the tree after loading. DevTools' Elements panel shows the live DOM, not the original file.
05Definitions
DOM
The Document Object Model: the browser's tree of objects representing a page.
Node
Any item in the DOM tree: an element, a text node or a comment.
Element
A node created from an HTML tag, such as a p or li element.
Text node
A node holding the text between tags, including whitespace.
Parent, child and sibling
Relationships in the DOM tree: the container, the elements directly inside, and elements at the same level.
ex-051-04How deep is an element? Browser page (sandboxed preview)
Walking up with parentElement until there is none measures depth.
function depth(el) {
let d = 0;
while (el.parentElement) {
d++;
el = el.parentElement;
}
return d;
}
console.log(document.documentElement.tagName);
console.log(document.body.children.length);
console.log(depth(document.querySelector("p")));
Sample input
None
Expected output
HTML
2
4
Common mistake
Forgetting that html and body are part of the tree too.
Try this
Return the list of tag names on the way up instead of a number.
const title = document.getElementById("title");
const list = document.getElementById("list");
// TODO: print "Groceries: 4 items" using the DOM (do not type the number)
Page outline
Walk the DOM tree recursively.
// Write outline(el, depth = 0)
09Prediction
Commit to an answer first, then run the real code to compare.
A help widget needs the page's headings to build a table of contents. It walks the DOM tree from the main element and collects every h2, without the page author adding anything special.
// In a page: [...document.querySelector("main").children]
// .filter((el) => el.tagName === "H2")
// .map((h) => h.textContent)
console.log("Collect the h2 elements inside main");
12Knowledge check
1. What is the DOM?
The HTML file on disk
The browser's tree of objects representing the page
A CSS framework
The JavaScript console
2. What is printed for <ul id="m"><li>A</li><li>B</li></ul>?
5. What does the tagName of a paragraph element print?
p
P
<p>
paragraph
6. To get the last item of a list element list, which is more robust?
list.children[2]
list.lastElementChild
list.childNodes[2]
list.lastChild
13Solutions and tests
Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.
Automated acceptance tests for this lesson
These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.
Read the last menu item: Prints Contact; No fixed index 2 or 3
List summary: Prints the summary; Counts with children
Page outline: Prints the outline; Works on a smaller tree
The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-11-the-document-object-model/lesson-051-understanding-the-dom-tree/. Every example on this page is generated from those files.
These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.
15Summary and next steps
The DOM is a tree of objects built from the page.
Elements have parents, children and siblings.
Text is stored in separate text nodes.
children and the *ElementChild properties skip text nodes.
Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.
Concept explanationthe DOM tree
Context: I am learning the DOM tree in JavaScript.
Task: Explain the DOM tree with a small HTML page, showing parents, children, siblings and text nodes.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code predictionthe DOM tree drill
Context: I have practised the DOM tree.
Task: Give me six small HTML snippets with DOM navigation code and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debuggingthe DOM tree bug
Context: My code reads firstChild and gets an empty value instead of the element.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generationthe DOM tree practice
Context: I finished the the DOM tree exercises.
Task: Create three exercises that walk and summarise a DOM tree.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code reviewthe DOM tree review
Context: Here is my code that uses the DOM tree.
Task: Review my DOM navigation code and suggest more robust properties.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.