DOM
▶DOM Fundamentals
🙋♂️ What?
DOM (Document Object Model) is JavaScript's representation of a web page. It allows JavaScript to find elements, respond to user actions, and update what appears on the screen.
🤔 Why?
Without the DOM, JavaScript can run code, but it cannot interact with the page. The DOM is what lets JavaScript read, change, add, and remove HTML elements.
In short:
The DOM is the bridge between HTML and JavaScript.
🧩 Fundamentals
Before learning individual DOM methods, remember this pattern:
Select an element - Listen for an event - Read or change something
Almost every interactive webpage follows this flow.
▶1. Selecting Elements
🙋♂️ What?
Selecting means finding an HTML element so JavaScript can work with it.
const heading = document.getElementById("title");🤔 Why?
JavaScript cannot change, read, or listen to an element unless it knows which element you mean.
Think of it like getting a reference to something before you can use it.
🧩 How?
Give the element an id:
<h1 id="title">Hello</h1>
<button id="startBtn">Start</button>
<input id="nameInput" />Then select it:
const title = document.getElementById("title");
const button = document.getElementById("startBtn");
const input = document.getElementById("nameInput");The value passed to getElementById() must match the HTML id exactly.
🧩 Common Pattern
const element = document.getElementById("someId");🏋️ Practice
HTML:
<h1 id="welcome">Welcome!</h1>Select the heading and log it to the console.
💡 Solution
const heading = document.getElementById("welcome");
console.log(heading);📌 Summary
| Task | Code |
|---|---|
| Give an element an ID | id="title" |
| Select an element | document.getElementById("title") |
| Store it in a variable | const title = ... |
▶2. Changing Content
🙋♂️ What?
Change or read the text inside an element.
heading.textContent = "New Title";🤔 Why?
This is how JavaScript updates what users see on the page.
🧩 How?
HTML:
<h1 id="title">Old Title</h1>JavaScript:
const heading = document.getElementById("title");
heading.textContent = "Hello World";Read the text:
console.log(heading.textContent);textContent vs innerHTML
textContent
Treats everything as plain text.
heading.textContent = "<b>Hello</b>";Result:
<b>Hello</b>innerHTML
Interprets HTML tags.
heading.innerHTML = "<b>Hello</b>";Result:
Hello
Use textContent by default. Use innerHTML only when you intentionally want to insert HTML.
🏋️ Practice
HTML:
<h1 id="welcome">Old text</h1>Change the text to "Welcome!".
💡 Solution
const heading = document.getElementById("welcome");
heading.textContent = "Welcome!";📌 Summary
| Task | Code |
|---|---|
| Change text | element.textContent = "Hi" |
| Read text | element.textContent |
| Insert HTML | element.innerHTML = "<b>Hi</b>" |
▶3. Event Listeners
🙋♂️ What?
Run code when something happens.
Examples:
- Click
- Typing
- Form submit
- Mouse movement
🤔 Why?
Without events, your page cannot react to users.
🧩 How?
General pattern:
element.addEventListener("event", callback);Example:
<button id="startBtn">Click me</button>const button = document.getElementById("startBtn");
button.addEventListener("click", () => {
console.log("Button clicked");
});The callback function is not executed immediately.
You hand it to the browser, and the browser runs it when the event occurs.
Common Events
| Event | When it happens |
|---|---|
| "click" | User clicks |
| "input" | User types |
| "submit" | Form submitted |
| "change" | Value changes |
🏋️ Practice
HTML:
<button id="helloBtn">Say Hello</button>Log "Hello!" when clicked.
💡 Solution
const button = document.getElementById("helloBtn");
button.addEventListener("click", () => {
console.log("Hello!");
});📌 Summary
| Task | Code |
|---|---|
| Listen for an event | addEventListener() |
| Event name | "click" |
| Callback function | () => {} |
▶Project: Counter
Goal
Build a counter with increase and decrease buttons.
Requirements
- Show a number on screen, starts at 0
- Two buttons: "+" and "-"
- Click "+" increases by 1
- Click "-" decreases by 1
- Number never goes below 0
Expected Behavior
- Start: 0
- Click "+": 1
- Click "+": 2
- Click "-": 1
- Click "-": 0
- Click "-": stays 0
Final code
const countEl = document.getElementById("count");
const plusBtn = document.getElementById("plusBtn");
const minusBtn = document.getElementById("minusBtn");
let count = 0;
plusBtn.addEventListener("click", () => {
count++;
countEl.textContent = count;
});
minusBtn.addEventListener("click", () => {
if (count > 0) {
count--;
countEl.textContent = count;
}
});What You Built With
| Concept | Where |
|---|---|
| getElementById | Grab count, buttons |
| addEventListener | Handle clicks |
| textContent | Update the number |
| let variable | Track the count |
▶4. Reading Input Values
🙋♂️ What?
Get what the user typed.
input.value🤔 Why?
Most interactive applications depend on user input.
Examples:
- Search boxes
- Login forms
- Todo lists
- Calculators
🧩 How?
HTML:
<input id="nameInput" />
<button id="greetBtn">Greet</button>JavaScript:
const input = document.getElementById("nameInput");
const button = document.getElementById("greetBtn");
button.addEventListener("click", () => {
console.log(input.value);
});Important
Input values are always strings.
console.log(typeof input.value);Output:
stringConvert to a number when needed:
const age = Number(input.value);🏋️ Practice
HTML:
<input id="nameInput" />
<button id="helloBtn">Say Hello</button>Print:
Hello, Sarahusing whatever the user typed.
💡 Solution
const input = document.getElementById("nameInput");
const button = document.getElementById("helloBtn");
button.addEventListener("click", () => {
console.log(`Hello, ${input.value}`);
});📌 Summary
| Task | Code |
|---|---|
| Read value | input.value |
| Convert to number | Number(input.value) |
| Use with events | Inside a callback |
▶Project: Tip Calculator
Goal
Calculate tip from a bill amount and percentage.
Requirements
- Input for bill amount
- Input for tip percentage
- Button: "Calculate"
- On click: read both values, calculate tip, show result
Expected Behavior
- Bill: 200, Percentage: 10 → Tip: 20
- Bill: 150, Percentage: 20 → Tip: 30
Final code
const billInput = document.getElementById("billInput");
const tipInput = document.getElementById("tipInput");
const button = document.getElementById("calcBtn");
const result = document.getElementById("result");
button.addEventListener("click", () => {
const bill = Number(billInput.value);
const percentage = Number(tipInput.value);
const tip = bill * (percentage / 100);
result.textContent = `Tip: ${tip}`;
});What You Built With
| Concept | Where |
|---|---|
| getElementById | Grab inputs, button, result |
| addEventListener | Handle click |
| input.value | Read user input |
| Number() | Convert string to number |
| textContent | Display the tip |
| template literal | Format the output |
▶5. Creating and Removing Elements
🙋♂️ What?
Create new HTML elements or remove existing ones.
🤔 Why?
Dynamic applications constantly add and remove content.
Examples:
- Todo items
- Chat messages
- Notifications
- Search results
🧩 How?
Step 1: Create
const li = document.createElement("li");Step 2: Add Content
li.textContent = "New item";Step 3: Add to the Page
list.appendChild(li);Full example:
<ul id="myList"></ul>
<button id="addBtn">Add Item</button>const list = document.getElementById("myList");
const button = document.getElementById("addBtn");
button.addEventListener("click", () => {
const li = document.createElement("li");
li.textContent = "New item";
list.appendChild(li);
});Removing Elements
li.remove();🏋️ Practice
HTML:
<ul id="taskList"></ul>
<button id="addTask">Add Task</button>Add a new task every time the button is clicked.
💡 Solution
const button = document.getElementById("addTask");
const list = document.getElementById("taskList");
button.addEventListener("click", () => {
const li = document.createElement("li");
li.textContent = "New task";
list.appendChild(li);
});📌 Summary
| Task | Code |
|---|---|
| Create element | createElement() |
| Add text | .textContent |
| Add to page | .appendChild() |
| Remove | .remove() |
▶Project: Todo List
Goal
Build a dynamic todo list.
Requirements
- Input field for task name
- Button: "Add"
- On click: create a new list item, add it to the list, clear the input
- Click any task to remove it
Expected Behavior
- Type "Buy milk", click Add → list shows: Buy milk
- Type "Study JS", click Add → list shows: Buy milk, Study JS
- Click "Buy milk" → list shows: Study JS
Final code
js
const input = document.getElementById("taskInput");
const button = document.getElementById("addBtn");
const list = document.getElementById("taskList");
button.addEventListener("click", () => {
const li = document.createElement("li");
li.textContent = input.value;
li.addEventListener("click", () => {
li.remove();
});
list.appendChild(li);
input.value = "";
});What You Built With
| Concept | Where |
|---|---|
| getElementById | Grab input, button, list |
| addEventListener | Add click and remove click |
| input.value | Read task name |
| createElement | Create new list item |
| textContent | Set task text |
| appendChild | Add to the list |
| .remove() | Delete on click |
▶DOM Cheat Sheet
// Select
const element = document.getElementById("id");
// Change text
element.textContent = "Hello";
// Listen for events
element.addEventListener("click", () => {});
// Read input
const value = input.value;
// Create element
const li = document.createElement("li");
// Add element
list.appendChild(li);
// Remove element
li.remove();
Formula:
- Select
- Listen
- Read
- Change