Course contentsShow
← Web Development
Lesson 703 of 2,98212. The Document Object ModelFree lesson

Best Practices for DOM Manipulation

Apply performance patterns: batch updates, minimize reflows, use fragments, and avoid innerHTML in loops.

Best Practices for DOM Manipulation

You'll learn how to write performant DOM manipulation code by batching updates, minimizing reflows, using fragments, and avoiding innerHTML in loops.

The Performance Problem

Every time you manipulate the DOM, the browser may need to recalculate layouts (reflow) and repaint the screen. These operations are expensive. Think of it like rearranging furniture: moving one chair at a time means walking back and forth repeatedly, but planning and moving everything in one trip is far more efficient.

Core Patterns for Performance

Batch Your Updates

Instead of modifying elements one at a time, group changes together:

// Inefficient: multiple reflows
const list = document.getElementById('myList');
for (let i = 0; i < 100; i++) {
    const item = document.createElement('li');
    item.textContent = `Item ${i}`;
    list.appendChild(item); // Reflow on each append!
}

Use Document Fragments

Fragments let you build a subtree off-DOM, then attach it once:

// Efficient: single reflow
const list = document.getElementById('myList');
const fragment = document.createDocumentFragment();

for (let i = 0; i < 100; i++) {
    const item = document.createElement('li');
    item.textContent = `Item ${i}`;
    fragment.appendChild(item); // No reflow yet
}

list.appendChild(fragment); // One reflow

Avoid innerHTML in Loops

Using innerHTML inside loops forces the browser to parse HTML repeatedly and destroys existing element references:

// Bad: parses HTML 100 times
for (let i = 0; i < 100; i++) {
    list.innerHTML += `<li>Item ${i}</li>`;
}

// Better: use createElement and fragments

Key Takeaway: Minimize DOM operations by batching updates with document fragments, avoiding repeated innerHTML assignments, and reducing the number of times you force the browser to recalculate layouts.