Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14
Chapter 6

DOM Tree, Nodes & Relationships

The document node tree, node types, and parent/child/sibling relationships.


The HTML DOM Document Node Tree

The node tree starts at the root node and branches to text nodes at the lowest level.

<html>
  <head>
    <title>My title</title>
  </head>
  <body>
    <a href="#">My link</a>
    <h1>My header</h1>
  </body>
</html>
document
  └─ html            (element)
       ├─ head       (element)
       │    └─ title (element) └─ text: "My title"
       └─ body       (element)
            ├─ a     (element, attribute: href) └─ text: "My link"
            └─ h1    (element) └─ text: "My header"

W3C HTML DOM Node Types

Node typeMeaning
Document nodeThe entire HTML document (the root).
Element nodeEvery HTML element (<p>, <div>, <span>...).
Text nodeThe text content inside HTML elements.
Attribute nodeEvery HTML attribute (id, class, href...).
Comment nodeAll HTML comments.

Node Relationships: Parent, Child, Sibling

  • Root node — the top node in the tree (has no parent).
  • Parent — every node has exactly one parent, except the root.
  • Children — a node can have zero or more child nodes.
  • Siblings — nodes that share the same parent.

Example

<html>
  <head><title>DOM Tutorial</title></head>
  <body>
    <h1>DOM Lesson One</h1>
    <p>Hello world!</p>
  </body>
</html>
  • <html> is the root node (no parent).
  • <html> is the parent of <head> and <body>.
  • <head> is the first child of <html>; <body> is the last child.
  • <title> has a text node: "DOM Tutorial".
  • <body> has two children: <h1> and <p>; they are siblings.

Activity — complete the code

Complete the code correctly to mark this lesson as complete automatically.

Complete the node types and relationships.

<!-- The entire document is a node -->
<!-- <p> is an node -->
<!-- The text inside <p> is a node -->
<!-- id="x" is an node -->
 
<!-- Relationships -->
<!-- <html> is the node (it has no parent) -->
<!-- <head> and <body> are of <html> -->