HTML DOM Nodes
In the HTML DOM, everything is a node. The DOM is considered a tree of nodes from the HTML.
DOM Nodes
According to the W3C 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
- The text inside HTML elements is a text node
- Each HTML attribute is an attribute node
- Comments are comment nodes
HTML DOM Tree of Nodes
The HTML DOM views an HTML document as a tree structure. This structure is called the tree of nodes:
HTML DOM Tree Example
Node Parents, Children, and Siblings
Nodes in the tree of nodes have hierarchical relationships.
We use terms like parent, child, and sibling to describe these relationships. A parent node has child nodes. Child nodes at the same level are called siblings (brothers or sisters).
- At the top of the node tree is the root (root node)
- Every node has a parent except the root (which has no parent)
- A node can have any number of child nodes
- Siblings are nodes with the same parent
The following image shows part of the node tree and the relationships between the nodes:
Consider the following HTML snippet:
<html>
<head>
<meta charset="utf-8">
<title>DOM Tutorial</title>
</head>
<body>
<h1>DOM Lesson 1</h1>
<p>Hello world!</p>
</body>
</html>
From the above HTML:
- The <html> node has no parent; it is the root node
- The <head> and <body> nodes have the <html> node as their parent
- The text node "Hello world!" has the <p> node as its parent
And:
- The <html> node has two child nodes: <head> and <body>
- The <head> node has two child nodes: <meta> and <title>
- The <title> node has one child node: the text node "DOM Tutorial"
- The <h1> and <p> nodes are sibling nodes and also child nodes of <body>
Also:
- 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
Warning!
A common mistake in DOM processing is expecting element nodes to contain text.
In this example: <title>DOM Tutorial</title>
, the element node <title>
contains a text node with the value "DOM Tutorial".
You can access the value of the text node through the innerHTML property of the node.
You will learn more about the innerHTML property in later chapters.