1 WEB FOUNDATIONS

DOM Manipulation

🎯 DOM Manipulation: Bringing HTML to Life

Your browser's engine does something incredibly complex when it reads an HTML file. It translates the raw text (<h1>Title</h1>) into an enormous JavaScript Object called the DOM (Document Object Model).

If HTML is a physical building, the DOM is the blueprint inside the architect's computer. By using JavaScript to alter the blueprint in real-time, the building instantly morphs and changes its shape.


1️⃣ What is the DOM?

The document object is injected into your global scope by the browser. Through document, you have God-like power over the entire webpage.


2️⃣ Selecting Elements (Querying the DOM)

Before you can change a button's color to red, you have to mathematically target and select that specific button.

The Old APIs (Do not use these):

  • document.getElementById('save-btn')
  • document.getElementsByClassName('card') (Returns a frustrating, hard-to-use HTMLCollection, not a real Array).

The Modern API (Use this exclusively): The querySelector methods allow you to pass exact CSS selectors directly into JavaScript.

// Selects the FIRST element that matches the CSS class
const saveButton = document.querySelector('.btn-save');

// Selects ALL elements that match, returning a NodeList (which behaves like an Array)
const allCards = document.querySelectorAll('.product-card');

allCards.forEach(card => {
    console.log("Found a card!");
});

3️⃣ Manipulating Elements (Changing the Blueprint)

Once you grab an element, you can modify its text, its styling, or its structural classes.

<h1 id="title" class="text-gray">Old Title</h1>
const titleElement = document.querySelector('#title');

// 1. Changing Text Content
titleElement.textContent = "New Dynamic Title!";

// 2. Modifying Classes
// Never use titleElement.className = "text-red", it aggressively deletes all old classes.
titleElement.classList.remove('text-gray');
titleElement.classList.add('text-red');

// Toggle acts like a lightswitch. If it has the class, remove it. If it doesn't, add it.
titleElement.classList.toggle('is-hidden'); 

// 3. Modifying Inline Styles Directly (Use sparingly, classes are better)
titleElement.style.backgroundColor = "blue";
titleElement.style.padding = "20px"; // Notice CSS 'padding-top' becomes camelCase 'paddingTop' in JS.

4️⃣ Event Listeners (Reacting to the User)

A website that doesn't react to mouse clicks or keyboard typing is dead. Events are signals fired by the browser when something happens. We use addEventListener to tell JavaScript: "Wait here, and execute this function specifically when the event happens."

const submitBtn = document.querySelector('.submit-btn');

submitBtn.addEventListener('click', function(event) {
    // This code only runs WHEN the user clicks the button
    console.log("Button was heavily clicked!");
    
    // The 'event' object contains massive amounts of data:
    console.log("Mouse X coordinates:", event.clientX);
});

The Default Behavior Problem

Many HTML elements have deep-rooted default behaviors.

  • Clicking a <a href=""> instantly abandons the current page to navigate.
  • Clicking <button type="submit"> inside a form instantly triggers a hard page refresh, wiping out the DOM.

As Single Page Application developers, we must violently stop these default actions.

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

form.addEventListener('submit', function(event) {
    // 🛑 Stops the browser from refreshing the page!
    event.preventDefault(); 
    
    console.log("Form intercepted. Handing data to API locally instead.");
});

5️⃣ Creating and Destroying Elements

You can conjure brand new HTML out of thin air using JavaScript and forcefully inject it into the page. This is the underlying mechanism of how React.js creates whole applications.

const container = document.querySelector('.list-container');

// 1. Create a brand new, empty <li> floating in memory (not on the screen yet)
const newListItem = document.createElement('li');

// 2. Modify it
newListItem.textContent = "Purchased Milk";
newListItem.classList.add('completed-task');

// 3. Inject it into the DOM so the user can see it
container.appendChild(newListItem);

// 4. Destroy an existing element forever
const oldItem = document.querySelector('.deprecated-task');
oldItem.remove();

6️⃣ The DOM is Slow (Why React Changed the Game)

While manipulating the DOM is powerful, it is computationally expensive. Every time you run document.createElement, the browser halts, recalculates all CSS rules, repaints pixels on the monitor, and struggles for milliseconds. Doing this 1,000 times in a loop will physically freeze the user's browser tab.

This slowness birthed tools like React.js. React uses a Virtual DOM—it does all the math in raw memory (which is blazing fast), figures out the absolute minimum number of DOM updates needed, and executes them instantly.


💡 Summary API Dictionary

OperationThe Modern JS Approach
Find One Itemdocument.querySelector('#my-id')
Find Many Itemsdocument.querySelectorAll('.my-class')
Change Textelement.textContent = "Hello"
Manage CSSelement.classList.add(), element.classList.remove()
Listen to Clickselement.addEventListener('click', fn)
Stop Refreshingevent.preventDefault()
Delete Itemelement.remove()

Knowledge Check

Complete this quick quiz to verify your understanding and unlock the next module.