← JS Mastery | Module 5: DOM Manipulation Creating, Modifying & Removing Elements
Module 5

Creating, Modifying & Removing Elements

⏱ 20 min read ● Intermediate 🆓 Free

Creating Elements

// createElement — create a new element:
const div = document.createElement("div");
div.className = "card";
div.id = "card-1";
div.textContent = "Hello!";
div.style.color = "gold";

// createTextNode:
const text = document.createTextNode("Hello World");

// cloneNode — copy existing element:
const original = document.querySelector(".template");
const clone = original.cloneNode(true);  // true = deep clone (includes children)

// Build complex structures:
function createCard(title, description) {
  const card = document.createElement("div");
  card.className = "card";
  
  const heading = document.createElement("h2");
  heading.textContent = title;
  
  const para = document.createElement("p");
  para.textContent = description;
  
  card.appendChild(heading);
  card.appendChild(para);
  
  return card;  // return without inserting — caller decides where
}

Inserting Elements

const parent = document.querySelector("#container");
const child = document.createElement("div");

// Classic:
parent.appendChild(child);                         // append at end
parent.insertBefore(child, parent.firstChild);     // insert at start

// Modern (preferred):
parent.append(child);          // append element or text
parent.append("text string");  // can append strings too!
parent.append(el1, el2, el3);  // append multiple!

parent.prepend(child);         // insert at beginning

// Insert relative to element:
child.before(newEl);           // insert before child (as sibling)
child.after(newEl);            // insert after child (as sibling)
child.replaceWith(newEl);      // replace child with newEl

// innerHTML — fast for complex HTML (be careful with user input!):
parent.innerHTML = '
Content
'; parent.innerHTML += '

More content

'; // AVOID — re-parses whole thing // insertAdjacentHTML — more targeted: el.insertAdjacentHTML("beforebegin", "

Before element

"); el.insertAdjacentHTML("afterbegin", "

First child

"); el.insertAdjacentHTML("beforeend", "

Last child

"); el.insertAdjacentHTML("afterend", "

After element

");

Removing & Replacing Elements

// Remove element:
const el = document.querySelector(".remove-me");
el.remove();  // modern, clean

// Old way (still works):
el.parentElement.removeChild(el);

// Remove all children:
const container = document.querySelector("#container");
container.innerHTML = "";          // fast but loses event listeners
while (container.firstChild) {
  container.removeChild(container.firstChild);  // preserves listeners
}
container.replaceChildren();       // modern way to clear children

// Replace element:
const old = document.querySelector(".old");
const newEl = document.createElement("div");
old.replaceWith(newEl);  // modern

// Efficient bulk DOM operations with DocumentFragment:
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
  const li = document.createElement("li");
  li.textContent = `Item ${i}`;
  fragment.appendChild(li);  // no reflow — fragment is off-screen
}
list.appendChild(fragment);  // single reflow at end — much faster!

Templates

// HTML template element (best practice):
// HTML: 

function createCardFromTemplate(title, desc) {
  const template = document.querySelector("#card-template");
  const clone = template.content.cloneNode(true);
  
  clone.querySelector(".card-title").textContent = title;
  clone.querySelector(".card-desc").textContent = desc;
  
  return clone;
}

const card = createCardFromTemplate("Hello", "World");
document.querySelector("#container").appendChild(card);

⚡ Key Takeaways

🎯 Practice Exercises

EXERCISE 1

Build a function that renders a list of items from an array. Use DocumentFragment for performance. Include a "clear all" button.

EXERCISE 2 — CHALLENGE

Create a modal component: a function that accepts title and content, creates modal HTML, appends it to body, and adds a close button that removes it. Pressing Escape should also close it.

← Events