Skip to content
Guest
Learn JavaScript · Course Syllabus Show lessons
DOM & Browser APIs · 8 min read · Beginner

DOM Manipulation, classList & Fragments

Create, update, and remove DOM nodes cleanly using createElement, replaceChildren, classList.toggle, and DocumentFragment.

What you'll learn

  • Toggle CSS states cleanly with element.classList (add, remove, toggle)
  • Build and insert nodes safely with document.createElement and replaceChildren()
  • Batch multiple insertions efficiently without repeated layout reflows

Instead of manually stitching raw HTML strings (which risks XSS bugs), modern DOM APIs make creating and updating elements both safe and concise.

Everyday DOM Methods

MethodWhat It Does
el.classList.toggle('open')Adds class if absent, removes if present
document.createElement('li')Creates a fresh element node
parent.replaceChildren(...nodes)Replaces all children cleanly in a single DOM update
el.remove()Removes the element from the DOM

Fill-in-the-Blank Exercise

Safe DOM Creation & classList

Create a button element, toggle its 'active' class, and insert it into the container.

const btn = document.('button');
btn.textContent = 'Pinned';
btn..toggle('active');
container.append(btn);

Try It Yourself

Dynamic Tag Chips with classList & remove()
Live Result
Console Output

No console output yet. Try calling console.log(...) in JS.

Check Your Understanding

Score: 0 / 1

1. What does `container.replaceChildren(nodeA, nodeB)` do?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind