What is the DOM?
The DOM: Your Page as Objects ๐ณ
The DOM (Document Object Model) is how JavaScript sees and interacts with HTML. It turns your HTML into objects that JavaScript can manipulate!
Why is the DOM Important?
Without the DOM, JavaScript couldn't:
- Change text on a page
- Add/remove elements
- Respond to clicks
- Create interactive websites!
HTML โ DOM Tree
Your HTML becomes a tree structure:
<html>
<body>
<h1>Hello</h1>
<p>World</p>
</body>
</html>
JavaScript sees this as:
document
โโโ html
โโโ body
โโโ h1 ("Hello")
โโโ p ("World")
Every HTML element becomes a node in this tree.
The document Object
document is your gateway to the entire page:
// Page information
console.log(document.title); // "My Page"
console.log(document.URL); // "https://..."
// Access elements
console.log(document.body); // The <body> element
console.log(document.head); // The <head> element
What Can You Do with the DOM?
| Action | Example |
|---|---|
| Read content | element.textContent |
| Change content | element.textContent = "New" |
| Add elements | parent.appendChild(child) |
| Remove elements | element.remove() |
| Change styles | element.style.color = "red" |
| Handle events | element.addEventListener("click", ...) |
Your Turn!
Access the document's title and store it in a variable.