You may remember from earlier chapters that classes represent specific entities. The Document Object Model (DOM) is a set of objects that represent the browser and the documents that make up the web page. The DOM objects are instances of classes that model the structure of the browser, HTML document, HTML elements, element attributes, and CSS. The below figure depicts the parent-child relationships between the DOM objects that make up a web page.
To utilize the DOM in JavaScript, we need to use the DOM global variables. In the next section, we will learn more about the DOM global variables, including their type. For now, let's get used to the idea of using JavaScript to interact with the DOM.
To start, we are going to use the window
and document
global variables.
As mentioned above, we will go into more detail on these variables and what they are later.
Example
Here, the window
and document
variables are used to print information about the web page to the browser's console.
1<!DOCTYPE html>
2<html>
3<head>
4 <title>Using DOM Variables</title>
5 <script>
6 console.log("the page title:", document.title);
7 console.log("the protocol:", window.location.protocol);
8 </script>
9</head>
10<body>
11 contents
12</body>
13</html>
Console Output
the page title: Using DOM Variables
the protocol: https:
The DOM plays a key part in making web pages dynamic. Since the DOM is a JavaScript representation of the web page, you can use JavaScript to alter the DOM and consequently, the web page. The browser will re-render the web page anytime changes are made via the DOM.
Note
Rendering is not the same action as loading.
In order to add or edit HTML elements with code, we need to be able to access them.
The method document.getElementById
will search for a matching element and return a reference to it.
We will go into more detail on how this method works in the next section.
Example
We can use document.getElementById
and element.append
to add text to a <p>
tag.
1<!DOCTYPE html>
2<html>
3<head>
4 <title>Add content using DOM</title>
5</head>
6<body>
7 <p id="main-text">Words about things...</p>
8 <script>
9 let p = document.getElementById("main-text");
10 p.append("More words about things");
11 console.log(p.innerHTML);
12 </script>
13</body>
14</html>
Console Output
Words about things... More words about things
<script>
¶In the previous example, notice the <script>
tag is placed below the <p>
tag in the HTML document. HTML documents are executed top down. Therefore, a
<script>
tag must come after any other elements that will be affected by the code
inside the <script>
. Later in the chapter, we will learn about another way to
handle this.
Question
What do the DOM objects represent?
Question
What is the value of p.innerHTML
?
1<p id="demo-text">Hello friend</p>
2<script>
3 let p = document.getElementById("demo-text");
4 console.log(p.innerHTML);
5</script>