/ Gists / Inefficient DOM Manipulations
On gists

Inefficient DOM Manipulations

JavaScript

demo.js Raw #

/*
Why It’s a Problem:
Direct DOM manipulation triggers reflows and repaints, slowing down rendering.
Inserting elements one by one instead of batching updates increases the number of re-renders.
Modifying styles directly forces layout recalculations.
*/

// BAD: Multiple reflows
for (let i = 0; i < 1000; i++) {
    const div = document.createElement('div');
    div.textContent = `Item ${i}`;
    document.body.appendChild(div);
}

// GOOD: Batch updates using DocumentFragment
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
    const div = document.createElement('div');
    div.textContent = `Item ${i}`;
    fragment.appendChild(div);
}
document.body.appendChild(fragment);