HTML DOM Nodes


In the HTML DOM, everything is a node. DOM is HTML viewed as a tree of nodes.


DOM nodes

According to the W3C's HTML DOM standard, everything in an HTML document is a node:

  • The entire document is a document node

  • Each HTML element is an element node

  • Text inside an HTML element is a text node

  • Each HTML attribute is an attribute node

  • Comments are comment nodes


HTML DOM node tree

HTML DOM treats HTML documents as a tree structure. This structure is called a node tree :

HTML DOM Tree Example

DOM HTML tree


Node parent, child and sibling

Nodes in a node tree have a hierarchical relationship with each other.

We use terms such as parent , child, and sibling to describe these relationships. Parent nodes have child nodes. Children of the same level are called siblings (brothers or sisters).

  • In a node tree, the top node is called the root.

  • Every node has a parent, except the root (which has no parent).

  • A node can have any number of child nodes.

  • Siblings are nodes that have the same parent.

The image below shows part of the node tree, and the relationships between nodes:

Node tree

See the following HTML snippet:

<html>
  <head>
    <meta charset="utf-8">
    <title> DOM tutorial </title>
  </head>
  <body>
    <h1>DOM Course 1</h1>
    <p>Hello world!</p>
  </body>
</html>

From the HTML above:

  • The <html> node has no parent; it is the root node

  • The parent node of <head> and <body> is the <html> node

  • The parent of the text node "Hello world!" is the <p> node

And:

  • The <html> node has two children: <head> and <body>

  • The <head> node has two children: <meta> and <title> nodes

  • The <title> node also has a child node: the text node "DOM Tutorial"

  • The <h1> and <p> nodes are siblings and children of <body>

And:

  • The <head> element is the first child of the <html> element

  • The <body> element is the last child of the <html> element

  • The <h1> element is the first child of the <body> element

  • The <p> element is the last child of the <body> element


Important!

A common mistake in DOM processing is expecting element nodes to contain text.

In this example: <title>DOM Tutorial</title> , the element node <title>, containing a text node with the value "DOM Tutorial" .

The value of a text node can be accessed through the node's innerHTML property.

You'll learn more about the innerHTML attribute in a later chapter.