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?