Browse Web basics Topics โ–ผ
Next โฏ

The DOM

๐Ÿ“‚ Behavior ๐Ÿ“˜ Lesson 5 of 5

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 textContent when 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

  1. Running Scripts Before HTML Loads (The null Error): If you put your <script> tag in the <head> without the defer attribute, the JavaScript runs before the browser has parsed the <body>. document.querySelector("button") returns null, causing TypeError: Cannot read properties of null (reading 'addEventListener'). Place scripts at the very end of <body> or add defer to <script src="..." defer>.
  2. 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);
  3. Using innerHTML with Untrusted Input: Always reach for textContent to 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.

Test your understanding of The DOM

Quick interactive practice questions with instant feedback.

Take Quiz โ†’