JavaScript – DOM & Building Real Projects
intermediate30 XP

The DOM – JavaScript Controls Your Webpage!

Learn how JavaScript reads and changes HTML elements in real-time — the skill behind every interactive webpage!

The DOM — JavaScript Talks to HTML! šŸ¤

The DOM (Document Object Model) is how JavaScript talks to your HTML. It treats every HTML element as an object you can read and change!

What is the DOM?

When a browser loads your HTML, it creates a tree of all the elements:

document └── html ā”œā”€ā”€ head │ └── title └── body ā”œā”€ā”€ h1 (id="title") ā”œā”€ā”€ p (class="intro") └── button (id="btn")

JavaScript can find any element in this tree and change it!

Selecting Elements

JavaScript
// By ID — returns ONE element
const title = document.getElementById("title");

// By CSS selector (like CSS!) — returns ONE element  
const intro = document.querySelector(".intro");
const title2 = document.querySelector("#title");

// By CSS selector — returns ALL matching elements
const allParagraphs = document.querySelectorAll("p");
const allCards = document.querySelectorAll(".card");

Changing Content

JavaScript
const title = document.getElementById("title");

// Change the text
title.textContent = "New title! šŸŽ‰";

// Change HTML inside the element
title.innerHTML = "Title with <strong>bold</strong>!";

Changing Styles

JavaScript
const box = document.querySelector(".box");

box.style.backgroundColor = "purple";
box.style.color = "white";
box.style.fontSize = "24px";
box.style.display = "none";   // hide the element!

Adding and Removing Classes

JavaScript
const card = document.querySelector(".card");

card.classList.add("highlighted");     // add a CSS class
card.classList.remove("highlighted");  // remove it
card.classList.toggle("active");       // add if not there, remove if there!

Reading Input Values

JavaScript
const nameInput = document.querySelector("#name-input");
const value = nameInput.value;   // gets what the user typed!
console.log("User typed: " + value);

🌟 Live Example: Real-Time Greeting

HTML
<input id="name" placeholder="Type your name...">
<button onclick="greet()">Say Hello! šŸ‘‹</button>
<h2 id="greeting"></h2>
JavaScript
function greet() {
  const name = document.getElementById("name").value;
  const greeting = document.getElementById("greeting");
  
  if (name) {
    greeting.textContent = "Hello, " + name + "! Welcome to the web! 🌐";
    greeting.style.color = "purple";
  } else {
    greeting.textContent = "Please type your name first!";
    greeting.style.color = "red";
  }
}

This is EXACTLY how Google's homepage works — you type in the search box, click the button, and JavaScript reads your input and does something with it! šŸ”

Quick check

01/3

What does DOM stand for?