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 start, we are going to use the
document global variables.
As mentioned above, we will go into more detail on these variables and what they are later.
document variables are used to print information about the web page to the browser's console.
1 2 3 4 5 6 7 8 9 10 11 12 13
<!DOCTYPE html> <html> <head> <title>Using DOM Variables</title> <script> console.log("the page title:", document.title); console.log("the protocol:", window.location.protocol); </script> </head> <body> contents </body> </html>
the page title: Using DOM Variables the protocol: https:
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.
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.
We can use
element.append to add text to a
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<!DOCTYPE html> <html> <head> <title>Add content using DOM</title> </head> <body> <p id="main-text">Words about things...</p> <script> let p = document.getElementById("main-text"); p.append("More words about things"); console.log(p.innerHTML); </script> </body> </html>
Words about things... More words about things
In the previous example, notice the
<script> tag is placed below the
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
<script>. Later in the chapter, we will learn about another way to
What do the DOM objects represent?
What is the value of
1 2 3 4 5
<p id="demo-text">Hello friend</p> <script> let p = document.getElementById("demo-text"); console.log(p.innerHTML); </script>