The DOM
Select elements, handle user interactions with event listeners, and dynamically update web pages using the Document Object Model.
When a web browser downloads an HTML document over the internet, it doesnโt just read it as a flat text file.
Instead, the browserโs engine parses all your nested tags and constructs a live, tree-structured object representation in computer memory called the DOM (Document Object Model).
The DOM is the living bridge between your HTML and your JavaScript:
The Web Architecture Bridge
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโ
โผ โผ
HTML File The Living DOM
<h1>Hello</h1> โโโบ Browser Parses Tags โโโบ document.querySelector("h1")
<button>Click</button> (JavaScript Objects & Nodes)
โ
โผ
Screen Updates Live!
Through the DOM, JavaScript can:
- Read and change any text or image on the screen.
- Add or remove CSS classes to trigger animations.
- Listen for user interactions (clicks, key presses, mouse movements).
- Create brand-new elements and insert them into the page without reloading.
Selecting Elements with querySelector
To manipulate an element, you first need to grab a reference to it. The modern, universal standard is document.querySelector(), which accepts any valid CSS selector string:
// 1. Select by HTML tag name (finds the first <header>)
const header = document.querySelector("header");
// 2. Select by class name (.btn-primary)
const saveButton = document.querySelector(".btn-primary");
// 3. Select by ID (#user-avatar)
const avatar = document.querySelector("#user-avatar");
// 4. Select ALL matching elements (returns a NodeList collection)
const allCards = document.querySelectorAll(".card");
allCards.forEach((card) => {
card.style.opacity = "1";
});
Updating Text and HTML: textContent vs innerHTML
Once you have an element, you can modify its content live:
const heading = document.querySelector("h1");
// Safe and recommended:
heading.textContent = "Updated from JavaScript!";
The Security Rule: Never Use innerHTML with User Input
You will often see element.innerHTML = "<span>Text</span>". While innerHTML can insert HTML tags, using it with user-supplied data (like comments or search queries) creates severe Cross-Site Scripting (XSS) vulnerabilities! A malicious user can submit <img src=x onerror="stealPasswords()">, and your page will execute their attack script.
[!IMPORTANT] Always use
textContentwhen displaying text or user-provided data. It safely renders everything as plain text.
Toggling CSS Classes
Instead of micromanaging inline styles (element.style.color = "blue"), professional developers toggle CSS classes using classList:
const banner = document.querySelector("#alert-banner");
// Add a class
banner.classList.add("visible");
// Remove a class
banner.classList.remove("hidden");
// Toggle a class on or off (e.g. Dark Mode switcher)
document.body.classList.toggle("dark-theme");
Listening to User Events: addEventListener
Web pages are event-driven: they sit patiently waiting for user actions. You react to user interactions using addEventListener():
element.addEventListener(eventType, callbackFunction);
โ โ โ
โผ โผ โผ
Target button "click" What function runs?
Here is a complete, working interactive click counter:
// Grab references to the HTML elements
const incrementBtn = document.querySelector("#inc-btn");
const display = document.querySelector("#counter-display");
let currentCount = 0;
// Listen for user clicks
incrementBtn.addEventListener("click", () => {
currentCount += 1;
display.textContent = currentCount;
if (currentCount >= 10) {
display.classList.add("milestone-reached");
}
});
Common Event Types
"click": User clicks or taps an element."input": User types into a text input or textarea (fires on every keystroke)."submit": User submits a<form>."keydown": User presses a key on their physical keyboard.
// Preventing form submission page refreshes
const form = document.querySelector("#login-form");
form.addEventListener("submit", (event) => {
event.preventDefault(); // Stop the browser from reloading the page
console.log("Form submitted via AJAX!");
});
Creating Elements Dynamically
You can generate brand new HTML elements out of thin air:
// 1. Create the new element
const newNotification = document.createElement("div");
// 2. Configure its classes and text
newNotification.className = "toast-notification";
newNotification.textContent = "Profile successfully saved!";
// 3. Attach it into the visible page
const container = document.querySelector("#notifications");
container.appendChild(newNotification);
Common Traps to Avoid
- Running Scripts Before HTML Loads (The
nullError): If you put your<script>tag in the<head>without thedeferattribute, the JavaScript runs before the browser has parsed the<body>.document.querySelector("button")returnsnull, causingTypeError: Cannot read properties of null (reading 'addEventListener'). Place scripts at the very end of<body>or adddeferto<script src="..." defer>. - Calling the Function Immediately in
addEventListener:// WRONG: Calls handleClick() immediately when the page loads! button.addEventListener("click", handleClick()); // CORRECT: Passes the function as a reference to run later on click button.addEventListener("click", handleClick); - Using
innerHTMLwith Untrusted Input: Always reach fortextContentto prevent XSS injection attacks.
Web Curriculum Complete!
Congratulations! You have completed the foundation of modern web engineering:
- Designing semantic content structure with HTML.
- Crafting beautiful visual designs and responsive typography with CSS.
- Governing element dimensions with the Box Model.
- Writing modern computational logic with JavaScript.
- Orchestrating live user interactions through the DOM.