What is the DOM and How Do We Use It?
Understand the Document Object Model and how JavaScript interacts with HTML.
The DOM (Document Object Model) is a programming interface that represents your HTML page as a tree of objects. JavaScript uses the DOM to read, modify, and respond to the web page.
The DOM Tree
When a browser loads an HTML page, it creates a DOM tree:
<!-- HTML -->
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1 id="title">Hello</h1>
<p class="intro">Welcome!</p>
</body>
</html>
Each HTML element becomes a node in the DOM tree that JavaScript can access and manipulate.
Selecting Elements
// By ID (returns one element)
let title = document.getElementById("title");
// By class name (returns a collection)
let intros = document.getElementsByClassName("intro");
// By tag name (returns a collection)
let paragraphs = document.getElementsByTagName("p");
// By CSS selector (modern — recommended)
let el = document.querySelector("#title"); // First match
let allP = document.querySelectorAll(".intro"); // All matches
Modifying Elements
let title = document.querySelector("#title");
// Change text
title.textContent = "New Title";
// Change HTML
title.innerHTML = "New <em>Title</em>";
// Change styles
title.style.color = "red";
title.style.fontSize = "2rem";
The document Object
document.title; // Get/set page title
document.URL; // Current page URL
document.body; // The <body> element
document.head; // The <head> element