DOM: Document Object Model

The DOM is the in-memory representation of the structure of an HTML document.
It is used to manipulate the HTML document with JavaScript objects.

The DOM is a tree of nodes, which represents the structure of an HTML document.
Each HTML element is a node, and each node has properties and methods.

Example of HTML structure

<html>
    <head>
        <title>My title</title>
        <meta charset="UTF-8"></meta>
    </head>
    <body>
        <h1>My title</h1>
        <p>My paragraph</p>
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
    </body>
</html>

The DOM is therefore the set of JavaScript objects that represent the structure of an HTML document.

Accessing DOM elements

You can access DOM elements with the document property.
You can access the properties and methods of these elements with the . property.

console.log(document.title); // My title
console.log(document.body); // <body>My title</body>
console.log(document.body.children); // [<h1>, <p>, <ul>]
// etc...

Modifying the DOM

You can also modify the DOM with JavaScript objects.

document.title = "New title";
document.body.children[0].innerHTML = "New title";
document.body.children[1].innerHTML = "New paragraph";
document.body.children[2].innerHTML = "New item 1";
document.body.children[3].innerHTML = "New item 2";
document.body.children[4].innerHTML = "New item 3";

So if you have an HTML page, you can access its elements and modify them with JS.
This is what we do when we want interactivity on a web page!
Because modifying a value without modifying the DOM is not possible! You absolutely have to modify the DOM or refresh the page!

Adding elements to the DOM

You can also add elements to the DOM with JavaScript objects.

document.body.appendChild(document.createElement("h1"));
document.body.children[0].innerHTML = "New title";

Deleting elements from the DOM

You can also delete elements from the DOM with JavaScript objects.

document.body.removeChild(document.body.children[0]);

Limitations and solutions

Except that as soon as we want to do complex things, we want to avoid typing 400 lines of code just to update the states
of the page, and update the values directly. We just want the value to update automatically.
To solve this problem and allow complex things to be done, this is where the famous 'JS frameworks' come in!