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
documentobject sitting at the top of the tree known as the root.
Then we have the
htmlelement as the child of the root. Its parent is
document. The children of
bodyare siblings to each other.
headelement has children
bodyelement has children
The root node is the
documentobject. Its child nodes are
!Doctype htmland the
htmlelement node whose parent node is the
The child nodes of
body. The text nodes
emptyare at the indentations and line breaks in the above HTML code, like for example after the
htmlopening tag and before the
metaopening tag. Technically speaking they aren't empty i.e they have spaces and new line characters but for simplicity we named them so.
headtag, the child nodes of
bodyinclude a comment node with node value
A commentand two element nodes -
phas a text node with node value
divhas a text node with node value
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
documentobject is the essence of HTML DOM. It is the root node and holds the entire document in it. All the useful stuff i.e the methods and properties are available on it and its children. You can't do any single thing to any single element without refering to the
documentobject. It is the global-scoped king of the DOM.
In the coming chapters all the properties and methods we show you will be performed starting from the