What is the DOM Tree?
The Document Object Model tree, or simply, the DOM tree is:
Each thing in an HTML document is related to one another by a means of connections laid out in this tree.
Starting from literally any element, you can go to any other element in the whole DOM by means of traversal (moving up or down the connective links between elements).Let's take the example of the following document and show you a simple picture of its DOM tree.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>DOM Tree</title> </head> <body> <!-- A comment --> <p>A paragraph</p> <div>A div</div> </body> </html>
First we have the whole document object sitting at the top of the tree known as the root.
Then we have the html element as the child of the root. Its parent is document. The children of html include head and body. head and body are siblings to each other.
- head element has children meta and title
- body element has children p and div
The root node is the document object. Its child nodes are !Doctype html and thehtml element node whose parent node is the document object.
The child nodes of html include head and body. The text nodes empty are at the indentations and line breaks in the above HTML code, like for example after the html opening tag and before the meta opening tag. Technically speaking they aren't empty i.e they have spaces and new line characters but for simplicity we named them so.
Skipping the head tag, the child nodes of body include a comment node with node value A comment and two element nodes - p and div
p has a text node with node value A paragraph. div has a text node with node value A div.
And we are done with the explanation of nodes! Remember the parent-child relationship between nodes. All the direct children of an element have the same parent which is the element itself.
The document object
In the coming chapters all the properties and methods we show you will be performed starting from the document object.