Modify Page Structure

Learning Objectives

Section 16.1: Modify an Existing Element

Changing Text Content

let element = document.querySelector("h1");

// Change text
element.textContent = "New Title";

// Get text
console.log(element.textContent);

Changing HTML Content

let container = document.querySelector(".content");

// Set HTML
container.innerHTML = "<p>New content</p>";

// Append HTML
container.innerHTML += "<p>More content</p>";

Changing Styles

let element = document.querySelector(".box");

// Inline styles
element.style.backgroundColor = "red";
element.style.fontSize = "20px";
element.style.padding = "10px";

// Multiple styles
element.style.cssText = "background: blue; color: white; padding: 10px;";

Limitations of Inline Styles

// ❌ Not ideal: Inline styles
element.style.backgroundColor = "red";

// ✅ Better: Use classes
element.classList.add("highlight");

Section 16.2: Adding a New Element

createElement

let newDiv = document.createElement("div");
newDiv.textContent = "I'm new!";
newDiv.className = "new-element";

document.body.appendChild(newDiv);

appendChild

let parent = document.querySelector(".container");
let child = document.createElement("p");
child.textContent = "New paragraph";

parent.appendChild(child);  // Add to end

Creating Complex Elements

let article = document.createElement("article");
article.className = "product";

let title = document.createElement("h2");
title.textContent = "Product Name";

let description = document.createElement("p");
description.textContent = "Product description";

article.appendChild(title);
article.appendChild(description);

document.body.appendChild(article);

Section 16.3: Variations on Adding Elements

insertBefore

let parent = document.querySelector("ul");
let newLi = document.createElement("li");
newLi.textContent = "First item";

// Insert at beginning
parent.insertBefore(newLi, parent.firstElementChild);

insertAdjacentHTML

let element = document.querySelector("h1");

// Insert after element
element.insertAdjacentHTML("afterend", "<p>Subtitle</p>");

// Insert before element
element.insertAdjacentHTML("beforebegin", "<nav>Menu</nav>");

// Insert inside before
element.insertAdjacentHTML("afterbegin", "<span>Prefix</span>");

// Insert inside after
element.insertAdjacentHTML("beforeend", "<span>Suffix</span>");

innerHTML vs insertAdjacentHTML

// innerHTML: replaces all content
element.innerHTML = "<p>New</p>";

// insertAdjacentHTML: adds without replacing
element.insertAdjacentHTML("afterend", "<p>New</p>");

Section 16.4: Replacing or Removing Nodes

Removing Elements

let element = document.querySelector(".delete-me");

// Remove element
element.remove();

// Remove from parent
element.parentElement.removeChild(element);

Replacing Elements

let oldElement = document.querySelector(".old");
let newElement = document.createElement("div");
newElement.textContent = "Replacement";

// Replace in parent
oldElement.parentElement.replaceChild(newElement, oldElement);

// Or simpler with replaceWith (newer API)
oldElement.replaceWith(newElement);

Section 16.5: Styling Elements

CSS Classes (Preferred)

<style>
    .active {
        background: green;
        color: white;
    }
    .inactive {
        background: gray;
    }
</style>

<script>
let element = document.querySelector("button");

element.classList.add("active");
element.classList.remove("inactive");
element.classList.toggle("active");
</script>

Inline Styles (When Necessary)

let element = document.querySelector(".box");

// Safe property assignment
element.style.width = "200px";
element.style.height = "200px";
element.style.backgroundColor = "blue";

// CSS text (avoid if possible)
element.style.cssText = "width: 200px; height: 200px; background: blue;";

Section 16.6: DOM Manipulations & Performance

Batch Operations

// ❌ Slow: Multiple reflows
for (let i = 0; i < 1000; i++) {
    let div = document.createElement("div");
    document.body.appendChild(div);  // Reflow each time
}

// ✅ Fast: Single reflow
let fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
    let div = document.createElement("div");
    fragment.appendChild(div);
}
document.body.appendChild(fragment);

Avoiding Excessive innerHTML

// ❌ Inefficient
for (let item of items) {
    container.innerHTML += `<p>${item}</p>`;  // Full reparse each time
}

// ✅ Efficient
let html = "";
for (let item of items) {
    html += `<p>${item}</p>`;
}
container.innerHTML = html;  // Single reparse

// ✅ Most efficient
let fragment = document.createDocumentFragment();
for (let item of items) {
    let p = document.createElement("p");
    p.textContent = item;
    fragment.appendChild(p);
}
container.appendChild(fragment);

Coding Challenges

Challenge 16.1: Adding a Paragraph

Task: Add a paragraph to a div using JavaScript

Challenge 16.2: Newspaper List

Task: Create a list of articles dynamically

Challenge 16.3: Mini-Dictionary

Task: Create words and definitions that can be added dynamically

Challenge 16.4: Updating Colors

Task: Change colors dynamically based on user input

Challenge 16.5: Information about an Element

Task: Display information (tag name, class,ID) about clicked elements

Key Takeaways

✅ createElement creates new elements
✅ appendChild adds elements to parent
✅ innerHTML and insertAdjacentHTML add HTML
✅ remove() deletes elements
✅ Use classes for styling, not inline styles
✅ Use DocumentFragment for batch operations

Quiz Questions


Next Module: Module 17 - React to Events