The DOM and Events
The DOM (Document Object Model) is the browser's live model of your page. JavaScript can find elements in it, change their text or style, and add or remove elements.
When the browser loads your HTML, it builds a tree of objects - one for each element. That tree is the DOM. JavaScript can't change the HTML file, but it can change this live tree, and the browser instantly updates what's on screen. That's how a page changes without reloading.
Events are things that happen: a click, a key press, typing in a box, scrolling, a page finishing loading. You "listen" for an event and give a function to run when it happens. Nearly all interactive features follow this pattern: find an element -> listen for an event -> change the page.
document.querySelector(".price")finds the first element matching a CSS selector.element.textContent = "..."changes its text safely.element.classList.toggle("dark")adds or removes a class.element.addEventListener("click", fn)runs a function when something happens.
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 16px; transition: background 0.3s; }
body.dark { background: #111827; color: #f9fafb; }
.count { font-size: 40px; font-weight: bold; }
</style>
</head>
<body>
<div class="count">0</div>
<button id="add">+1</button>
<button id="theme">Toggle dark mode</button>
<script>
let count = 0;
const display = document.querySelector(".count");
document.querySelector("#add").addEventListener("click", function () {
count++;
display.textContent = count;
});
document.querySelector("#theme").addEventListener("click", function () {
document.body.classList.toggle("dark");
});
</script>
</body>
</html>▶ Try it yourselfUse
textContent to show text a visitor typed. Putting their text into innerHTML can let harmful code run on your page.Key points
- The DOM is the browser's live tree of the page.
- Find elements with
querySelector; change them withtextContentandclassList. addEventListenerruns your code when something happens.- Use
textContent, notinnerHTML, for user text.
📝 Test yourself
1. What is the DOM?
2. Which is safer for showing text a visitor typed?
3. Fill in the method that reacts to clicks:
button.("click", run);
