Lesson 41 - Introduction to the DOM
The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of an HTML page and allows JavaScript to interact with elements dynamically. Read more about the DOM here.
What is the DOM?
- The DOM represents the document as a tree of objects.
- JavaScript can manipulate HTML elements, attributes, and styles using the DOM.
- It enables dynamic web pages where content updates without refreshing.
Basic DOM Structure
HTML elements are structured in a tree-like format:
Document
|-- html
| |-- head
| |-- body
| |-- h1
| |-- p
| |-- button
Each element in the HTML page becomes a node in the DOM.
Accessing the DOM in JavaScript
We can access different elements using JavaScript.
1. Accessing the Document Object
console.log(document); // Displays the entire DOM
2. Accessing the Title of the Page
console.log(document.title); // Gets the current page title
document.title = "New Page Title"; // Updates the title dynamically
3. Accessing Body and Head
console.log(document.body); // Returns the <body> section
console.log(document.head); // Returns the <head> section
Try Your Hand
Steps:
-
Create a File:
- Name it
lesson41-dom.html
.
- Name it
-
Write the Code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 41 - Introduction to the DOM</title> </head> <body> <h1 id="title">Hello, DOM!</h1> <button onclick="changeTitle()">Change Title</button> <script> function changeTitle() { document.getElementById("title").textContent = "DOM Updated!"; } </script> </body> </html>
-
Save and Open in a Browser.
-
Click the Button to See the Title Change.
Experiment
- Print the entire
document
object in the console. - Change the background color of the
<body>
using JavaScript. - Modify the text of a paragraph dynamically.
Key Takeaways
- The DOM represents an HTML page as a tree structure.
- JavaScript interacts with HTML using the DOM.
- The
document
object provides access to elements, attributes, and styles.