C
JavaScript/DOM/Lesson 13

DOM — *Manipulating HTML with JS*

30 min·theory
This chapter
1/2

DOM — *Manipulating HTML with JS*

🎯 By the end of this lesson

After reading through this lesson, you will be able to confidently do the following three things.

  • ✅ var · let · const differences + hoisting behavior
  • ✅ 7 types + the typeof trap (typeof null === 'object')
  • ✅ Script loading (defer · async · module) differences

Keep the learning objectives as a checklist and close the lesson once you can answer all of them.

What is the DOM?

Core Summary

DOM (Document Object Model) = the browser's representation of HTML as a JavaScript object tree. You manipulate this tree to dynamically change the page.

Tree Structure

code
document
└── html
    ├── head
    │   ├── title
    │   └── meta
    └── body
        ├── h1
        ├── div
        │   ├── p
        │   └── button
        └── footer

Each tag is a node. In JS, you can select, modify, add, and remove these nodes.

Selecting Elements

javascript
// 1️⃣ By ID — fastest, always returns 1 element (null if not found)
const el = document.getElementById('main');
//                  ↑ No # prefix! Just 'main'

// 2️⃣ By CSS selector — returns the first match (null if not found)
const btn = document.querySelector('.btn-primary');
//                    ↑ Use the CSS selector as-is, with # / .

// 3️⃣ By CSS selector — returns "all" matches
const items = document.querySelectorAll('.item');
// → NodeList (similar to an array but not a real array)
//   → items.forEach is OK, items.map is ❌ → convert with [...items].map

querySelector is the most flexible — use CSS selectors directly.

Modifying Content

javascript
const el = document.querySelector('#title');

// Text
el.textContent = "New title";

// HTML
el.innerHTML = "<strong>Bold</strong> title";

// Attributes
el.setAttribute('data-id', '42');
el.id = "new-id";

// Classes
el.classList.add('active');
el.classList.remove('hidden');
el.classList.toggle('open');

// Style (inline)
el.style.color = "red";
el.style.fontSize = "20px";

⚠️ The innerHTML trap — inserting raw user input creates an XSS attack risk:

javascript
el.innerHTML = userInput;        // ❌ XSS risk
el.textContent = userInput;       // ✅ Safe

Adding and Removing Elements

javascript
// Create
const newDiv = document.createElement('div');
newDiv.textContent = "Hello";
newDiv.classList.add('greeting');

// Add
parent.appendChild(newDiv);              // at the end
parent.insertBefore(newDiv, existing);   // at a specific position
parent.prepend(newDiv);                   // at the beginning

// Remove
el.remove();                              // remove self
parent.removeChild(child);                // remove child

Event Handling

javascript
const btn = document.querySelector('#submit');

btn.addEventListener('click', (event) => {
    event.preventDefault();   // prevent default behavior (e.g. form submit)
    console.log("Clicked!");
});

// Event object
btn.addEventListener('click', (e) => {
    console.log(e.target);       // clicked element
    console.log(e.clientX, e.clientY);   // mouse position
});

Form Handling

javascript
const form = document.querySelector('#login-form');

form.addEventListener('submit', async (e) => {
    e.preventDefault();

    const formData = new FormData(form);
    const email = formData.get('email');
    const password = formData.get('password');

    const res = await fetch('/api/login', {
        method: 'POST',
        body: JSON.stringify({ email, password }),
        headers: { 'Content-Type': 'application/json' }
    });
});

Modern Development — Direct DOM Manipulation Is Rare

Frameworks like React, Vue, and Svelte abstract away DOM manipulation. Developers only change state, and the framework handles DOM updates automatically.

Why you still need to know the DOM API:

  • Building libraries or simple pages
  • Debugging (browser developer tools)
  • Understanding framework internals

Summary

  • DOM = JS object representation of HTML
  • Select elements with querySelector
  • Manipulate with textContent, classList, and addEventListener
  • Modern development abstracts this via React etc., but the fundamentals are essential

⚡ Try it yourself — DOM API (mock document)

Due to browser sandbox restrictions, DOM manipulation is demonstrated using a *mock object* instead of the real document. See how `querySelector`, `textContent`, and `classList` work via console output.
✏️ JS 코드
📟 Console output
▶ Press the Run button
⚠️ Runs in a browser sandbox — only console.log() is supported; alert/fetch are not.

🤖 Try asking AI like this

Knowing the concepts from this lesson lets you give precise instructions to AI — not a vague "fix this", but requests with vocabulary — that is the starting point for saving tokens.

  • "Wrap this querySelector loop into a NodeList and use forEach"
  • "Refactor this event handler to use event delegation"
  • "Check this code for potential memory leaks (unreleased event listeners)"

Why does this reduce tokens?

Without knowing the concepts, you have to ask "What does that mean?" after every AI response. Those follow-up questions consume tokens. Learn the concepts once and the conversation ends in one go.

What is DOM? - JavaScript