When we open a web page in our browser, the browser retrieves the page’s HTML text and parses it. The browser builds up a model of the document’s structure and uses this model to draw the page on the screen
It is a data structure that you can read or modify. When it’s modified, the page on the screen is updated to reflect the changes.
We can imagine an HTML document as a nested set of boxes.
<!doctype html>
<html>
<head>
<title>My home page</title>
</head>
<body>
<h1>My home page</h1>
<p>Hello, I am Marijn and this is my home page.</p>
<p>I also wrote a book! Read it
<a href="http://eloquentjavascript.net">here</a>.
</p>
</body>
</html>
could be seen as
Trees
We call a data structure a tree when it has a branching structure, and has a single, well-defined root
We can visualize our document tree is as follows
The leaves are text nodes, and the arrows indicate parent-child relationships between nodes.
The Standard
The DOM wasn’t designed for just JavaScript. Thus, there are issues that are simply poor design. For example:
There is no way to create a new node and immediately add children or attributes to it.
Instead, we have to first create it and then add the children and attributes one by one, using side effects.
Moving Through the Tree
The following function scans a document for text nodes containing a given string and returns true when it has found one:
function talksAbout(node, string) {
if (node.nodeType == Node.ELEMENT_NODE) {
for (let i = 0; i < node.childNodes.length; i++) {
if (talksAbout(node.childNodes[i], string)) {
return true;
}
}
return false;
} else if (node.nodeType == Node.TEXT_NODE) {
return node.nodeValue.indexOf(string) > -1;
}
}
### Summary
- DOM is a data structure representing the browser’s model of the document. A JavaScript program can modify it to change the visible document.
- DOM is organized like a tree, in which elements are arranged hierarchically according to the structure of the document.
- The way a document is displayed can be influenced by styling
Document Structure
could be seen as
Trees
The Standard
Moving Through the Tree
console.log(talksAbout(document.body, "book")); // → true