You can navigate the node tree using node relationships.
- The entire document is a document node
- Every HTML element is an element node
- The text inside HTML elements are text nodes
- Every HTML attribute is an attribute node (deprecated)
- All comments are comment nodes
The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships.
- In a node tree, the top node is called the root (or root node)
- Every node has exactly one parent, except the root (which has no parent)
- A node can have a number of children
- Siblings (brothers or sisters) are nodes with the same parent
<head>
<title>DOM Tutorial</title>
</head>
<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>
</html>
From the HTML above you can read:
- <html> is the root node
- <html> has no parents
- <html> is the parent of <head> and <body>
- <head> is the first child of <html>
- <body> is the last child of <html>
and:
- <head> has one child: <title>
- <title> has one child (a text node): "DOM Tutorial"
- <body> has two children: <h1> and <p>
- <h1> has one child: "DOM Lesson one"
- <p> has one child: "Hello world!"
- <h1> and <p> are siblings
You can use the following node properties to navigate between nodes with JavaScript:
- parentNode
- children[index] / childNodes[index]
- firstChild / firstElementChild
- lastChild / lastElementChild
- nextSibling / nextElementSibling
- previousSibling /previousElementSibling
1. Get familiar with the code in the HTML file.
2. Then go to the JavaScript file to complete the exercise.
- www.w3schools.com
- AbeTavarez