JavaScript HTML DOM
The HTML DOM is a live, tree-shaped model of your page that JavaScript can read and rewrite while the page is running.
What is the DOM?
When a browser loads an HTML document, it does not keep the raw text around for scripting. Instead it parses the markup and builds an in-memory representation called the Document Object Model, or DOM. Every tag, attribute, and piece of text becomes an object that JavaScript can inspect and change. Because the DOM is live, any change you make to it is reflected on the screen almost immediately.
The DOM is organized as a tree. The document itself sits at the top, the <html> element is its main child, and every nested element becomes a branch or leaf below it. This parent-child structure is what lets you walk from one element to another and target exactly the piece of the page you want.
The document object
Your entry point into the DOM is the global 'document' object. It represents the whole page and exposes the methods and properties you use to find elements, create new ones, and respond to what the user does. Almost every DOM task you write will start from 'document'.
Reading and writing through the document object
<!DOCTYPE html>
<html>
<body>
<h1 id="main-title">Hello, World!</h1>
<script>
// Find an element by its id
const heading = document.getElementById("main-title");
// Read its current text
console.log(heading.textContent);
// Change what the user sees
heading.textContent = "Welcome to the DOM";
// The <title> shown in the browser tab is also part of the document
document.title = "Learning the DOM";
</script>
</body>
</html>What you can do with the DOM
- Find and read any element, attribute, or piece of text on the page
- Change the content and attributes of existing elements
- Add new elements and remove ones you no longer need
- Change the CSS styles and classes applied to elements
- React to user actions such as clicks, typing, and scrolling
Nodes in the tree
Exercise: JavaScript HTML DOM
What does document.getElementById() return when no element matches the given id?