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.
Global DOM Variables
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.
<!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:
Dynamic Web Page Using the DOM
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
<!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
Where to Put the
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
Check Your Understanding
What do the DOM objects represent?
- Word documents you have downloaded
- Directives of memory
- The browser window, HTML document, and the elements
What is the value of
<p id="demo-text">Hello friend</p> <script> let p = document.getElementById("demo-text"); console.log(p.innerHTML); </script>