Home/Concepts/DOM Manipulation
🌐
Intermediate⏱ 15 min#08 / 08

DOM Manipulation

Interacting with the Page

The DOM (Document Object Model) is how JavaScript talks to HTML. Using DOM methods, you can select elements, change content and styles, create new elements, and respond to user actions - all without reloading the page.

Your Progress0/8 complete
0 visited0%
💡 Real-World Analogy

The DOM is a puppet show. HTML is the puppets on stage. JavaScript is the puppeteer pulling strings. With DOM methods, you can make any puppet move, change costume, appear, disappear, or respond when the audience clicks them - live, without resetting the stage.

🔑 Key Concepts

Selecting Elements

getElementById, querySelector, querySelectorAll - pick any element like a CSS selector.

Modifying Content & Style

textContent, innerHTML, style, classList.add/remove/toggle - change what users see.

Events

addEventListener responds to clicks, keypresses, form submits, and more user interactions.

💻 Code Examples

1Selecting Elements
dom.js
1// By ID - returns ONE element
2let title = document.getElementById("main-title");
3 
4// querySelector - CSS selector, returns FIRST match
5let btn = document.querySelector(".submit-btn");
6let input = document.querySelector("#email");
7let heading = document.querySelector("h2");
8 
9// querySelectorAll - returns ALL matches (NodeList)
10let allCards = document.querySelectorAll(".card");
11let allInputs = document.querySelectorAll("input");
12 
13// Loop over NodeList
14allCards.forEach(card => {
15 card.style.border = "2px solid #6366f1";
16});
2Changing Content & Styles
dom.js
1let box = document.querySelector(".box");
2 
3// Text content (safe - no HTML parsing)
4box.textContent = "Hello World";
5 
6// innerHTML (parses HTML - use carefully)
7box.innerHTML = "<strong>Hello</strong> World";
8 
9// Inline styles
10box.style.color = "#6366f1";
11box.style.backgroundColor = "#0f172a";
12box.style.fontSize = "1.5rem";
13 
14// CSS classes (preferred over inline styles)
15box.classList.add("active");
16box.classList.remove("hidden");
17box.classList.toggle("dark-mode");
18box.classList.contains("active"); // true
19 
20// Attributes
21box.setAttribute("data-id", "42");
22box.getAttribute("data-id"); // "42"
3Events & Creating Elements
dom.js
1// Listen for events
2let btn = document.querySelector("#myBtn");
3 
4btn.addEventListener("click", function(event) {
5 console.log("Clicked at:", event.clientX, event.clientY);
6 event.target.textContent = "Clicked!";
7});
8 
9// Common events: click, input, submit, keydown
10 
11// Create new elements dynamically
12let newDiv = document.createElement("div");
13newDiv.textContent = "I was created by JavaScript";
14newDiv.className = "dynamic-card";
15document.body.appendChild(newDiv);
16 
17// Insert before an existing element
18let parent = document.querySelector(".container");
19let ref = document.querySelector(".reference");
20parent.insertBefore(newDiv, ref);

⚠️ Common Mistakes

❌ Mistake

Running DOM code before page loads

✅ Fix

Put script at end of body, or use DOMContentLoaded event, or defer attribute on script tag.

❌ Mistake

Setting innerHTML with user input

✅ Fix

Use textContent for plain text. Sanitize any HTML from user input to prevent XSS attacks.

❌ Mistake

querySelector returns null - not checked

✅ Fix

Always check if querySelector returned null before using the result, or your code will crash.

📋 Quick Reference

document.getElementById("id")document.querySelector(".class")document.querySelectorAll("tag")el.textContent = "text"el.innerHTML = "<b>html</b>"el.classList.toggle("cls")el.addEventListener("click", fn)document.createElement("div")

Live Code Playground

Edit the code and press ▶ Run to see output instantly.

dom_playground.js
⟳ Loading editor...
Interactive DOM Sandbox

Hello, DOM World! 🌐

This is a live sandbox element. Use your code to mutate me.

💾 Auto-saved
// Press ▶ Run Code to execute and view output console logs...
🔀
← Previous
Conditionals
Challenge Mode