DOM Manipulation

What is the DOM?

The DOM (Document Object Model) is a JavaScript representation of the HTML page. Think of the DOM as a tree of nodes (elements, text nodes, etc.) that you can read from and change with JavaScript. When you change the DOM, the browser updates what the user sees.

Why We Use the DOM?

The DOM is how browsers represent your webpage internally. Without the DOM, HTML would just be static. The DOM makes it interactive because JavaScript can read and modify it.

Example

HTML → A recipe written on paper.
DOM → A digital recipe book you can edit live (change ingredients, add steps, highlight text).

We Use DOM Manipulation To:

1. Selecting Elements

Methods

Advantages

Disadvantages

Example

<p id="intro">Hello!</p>
<p class="fruit">Apple</p>
<p class="fruit">Banana</p>

<script>
const byId = document.getElementById("intro");
const firstFruit = document.querySelector(".fruit");
const allFruits = document.querySelectorAll(".fruit");
</script>

Real-life Analogy

Like searching for a specific person:
getElementById = calling someone by unique ID card number.
querySelector = calling someone by their clothing (CSS style).
querySelectorAll = gathering a group wearing the same uniform.

2. Changing Content / Style

Content

Style

Example

<p id="msg">Old text</p>

<script>
const msg = document.getElementById("msg");
msg.textContent = "New safe text";
msg.innerHTML = "<b>Bold text</b>";
msg.style.color = "red";
msg.classList.add("highlight");
</script>

Advantages

Disadvantages

3. Event Listeners

Method

element.addEventListener("eventType", callback);

Advantages

Disadvantages

Example

<button id="btn">Click Me</button>

<script>
const btn = document.getElementById("btn");
btn.addEventListener("click", () => alert("Clicked!"));
</script>

Real-life Analogy

Like installing a doorbell:
Event = someone presses the button.
Listener = you hearing it and opening the door.

4. Creating / Removing Elements

Methods

Advantages

Disadvantages

Example

<ul id="list"></ul>

<script>
const list = document.getElementById("list");
const li = document.createElement("li");
li.textContent = "New Item";

list.appendChild(li);
</script>

Real-life Analogy

Like adding/removing notes on a notice board dynamically.