JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 11: The Document Object ModelLesson 51 of 150About 40 minutes

Lesson 51: Understanding the DOM tree

01Opening question

A web page looks like text and boxes, but JavaScript sees something else. What does a page look like to your code?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

The HTML panel holds a list. JavaScript reads it as objects: the list element, its children and their text.

const menu = document.getElementById("menu");
console.log(menu.tagName, menu.children.length);
console.log(menu.firstElementChild.textContent);

03Objective and prerequisites

Learning objective: Describe the DOM as a tree of nodes, move between parents, children and siblings, and tell element nodes from text nodes.

You need: Lesson 38: Nested objects and arrays, Lesson 1: What JavaScript is and where it runs

Skills practised: The DOM, The DOM tree.

04Explanation

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.

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.

Open the full glossary

06Visual learning object

DOM tree inspector. Type HTML and see the tree the browser builds: elements, text nodes and attributes, level by level.

Loading the interactive object…

Open the full DOM tree inspector page with its guided experiment.

07Examples

ex-051-01Children of an element Browser page (sandboxed preview)

children lists the elements directly inside another element.

const menu = document.getElementById("menu");
console.log(menu.tagName, menu.children.length);
console.log(menu.firstElementChild.textContent, menu.lastElementChild.textContent);
Sample input
None
Expected output
UL 3 Home Contact
Common mistake
Expecting tagName in lower case; HTML element names are reported in upper case.
Try this
Add a fourth item to the HTML and run again.
Source
examples/ex-051-01-children.js

ex-051-02Parents and siblings Browser page (sandboxed preview)

Every element knows its parent and its neighbours.

const body = document.getElementById("body");
console.log(body.parentElement.tagName);
console.log(body.previousElementSibling.textContent);
console.log(body.nextElementSibling);
Sample input
None
Expected output
ARTICLE Release notes null
Common mistake
Expecting nextElementSibling to be an empty element; it is null when there is none.
Try this
Log the article's parent tag too.
Source
examples/ex-051-02-relatives.js

ex-051-03Elements and text nodes Browser page (sandboxed preview)

childNodes includes text; children includes only elements.

const note = document.getElementById("note");
console.log(note.childNodes.length, note.children.length);
const kinds = [...note.childNodes].map((n) => n.nodeType === 1 ? n.tagName : "#text");
console.log(kinds.join(" "));
Sample input
None
Expected output
3 1 #text B #text
Common mistake
Using childNodes[0] and getting a text node instead of the element you wanted.
Try this
Remove the exclamation mark and predict both numbers.
Source
examples/ex-051-03-text-nodes.js

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.
Source
examples/ex-051-04-depth.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Read the last menu item

Use the length of children instead of a fixed index.

const items = document.getElementById("menu").children;
console.log(items[3].textContent);

List summary

Read a heading and count list items.

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.

// HTML: <ul id="u">
//   <li>A</li>
// </ul>
const u = document.getElementById("u");
console.log(u.childNodes.length, u.children.length);

What is printed?

10Debugging investigation

The first item shows a blank label

The shopping widget should say "First: Milk", but it shows "First: " with nothing after it.

const list = document.getElementById("list");
const first = list.childNodes[0];
const label = "First: " + first.textContent.trim();
console.log(label);

More cases in the Debugging Detective Laboratory

11Practical scenario

Reading a page before changing it

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>?

console.log(document.getElementById("m").children.length);
  • 2
  • 1
  • 0
  • 3

3. Which property skips text nodes?

  • childNodes
  • firstChild
  • children
  • nodeValue

4. Why is the label empty for <ul>\n <li>Milk</li>\n</ul>?

const label = document.querySelector("ul").firstChild.textContent.trim();
  • firstChild is the whitespace text node
  • li elements have no text
  • trim removes the text
  • ul has no children

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

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

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.

16AI learning prompts

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 explanation the 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 prediction the 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.
Debugging the 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 generation the 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 review the 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.