Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
A hands-on guide to the DOM techniques that frameworks hide: caching element references, batching inserts with a DocumentFragment, event delegation with closest(), data attributes that link elements to state, and rendering user text without opening an XSS hole. You build a small vanilla JavaScript to-do list. The finished to-do list was tested in jsdom.

React, Vue and Svelte hide the DOM, but they don't remove it. When a list renders slowly or a click handler fires on the wrong row, you need to know what the browser is doing underneath. This guide is for developers who know a framework and want to work with the DOM directly. You will build a small to-do list in plain JavaScript and pick up five techniques along the way. Here, "performance" means two concrete things: not forcing the browser to run layout more often than it needs to, and not adding more event listeners than you need.
This is part 6 of the Frontend & JavaScript Fundamentals series. It builds on scope and closures, because every event handler below is a closure over your state.
Key takeaways
- Look up elements once and keep the references; batch new nodes in a
DocumentFragmentand insert them in one go. - One click listener on the list, plus
closest(), handles every row, including rows added later. - Put user text on the page with
textContent, never withinnerHTML, so it can't run as code.
What the DOM is
The Document Object Model (DOM) is the tree of objects the browser builds from your HTML, which JavaScript can read and change. Every tag becomes a node. Methods such as querySelector() find nodes, and methods such as append() and remove() change the tree. Frameworks call DOM methods like these for you.
Here is the HTML for the app. It has a form and an empty list.
<form class="todo-form">
<input class="todo-input" name="text" aria-label="New to-do" />
<button type="submit">Add</button>
</form>
<ul class="todo-list"></ul>
1. Cache your element references
document.querySelector() returns the first element that matches a CSS selector, or null. MDN describes the search as a depth-first walk of the document. For a few static elements, there's no reason to repeat that walk inside every function. Look them up once when the script loads.
// Avoid: a new lookup every time the function runs
function readInput() {
const input = document.querySelector('.todo-input');
return input.value;
}
// Better: look up once, reuse everywhere
const elements = {
form: document.querySelector('.todo-form'),
input: document.querySelector('.todo-input'),
list: document.querySelector('.todo-list'),
};
The gain on a small page is tiny. The bigger win is clarity: every element the script depends on is listed in one place. If a class name changes, you fix it once.
2. Batch your DOM changes
Reflow is when the browser works out the position and size of parts of the page again, usually followed by a repaint. MDN's performance guide says DOM updates are expensive and advises you to batch them. Its tip for adding a large chunk of HTML is to build it first, typically in a DocumentFragment, and then append it all at once.
A DocumentFragment is a container that is not part of the page. You can add many nodes to it, then insert the whole fragment with one call.
function renderBatch(todos) {
const fragment = document.createDocumentFragment();
for (const todo of todos) {
fragment.append(createTodoElement(todo));
}
elements.list.append(fragment); // one insertion into the live DOM
}
You'll write createTodoElement() in section 4.
Don't oversell the fragment
The original version of this post said that appending 100 items one by one triggers layout 100 times. That isn't how browsers work. web.dev describes the normal order as your JavaScript first, then style, then layout, so writes alone don't trigger a layout each time. MDN's DocumentFragment page even says its speed benefit "is often overstated". Use a fragment because it keeps one clear insertion point.
The real cost comes from mixing reads and writes. If you change a style and then read a layout value such as offsetHeight, the browser has to run layout right away. web.dev calls this a forced synchronous layout. Doing it in a loop is called layout thrashing. So do all your reads first, then all your writes.
// Thrashing: each read forces layout because the previous write changed it
for (const item of items) {
item.style.height = `${item.offsetHeight * 2}px`;
}
// Fixed: all reads first, then all writes
const heights = items.map((item) => item.offsetHeight);
items.forEach((item, i) => { item.style.height = `${heights[i] * 2}px`; });
This pattern follows the web.dev layout thrashing article. Here items is an array of elements.
3. Use event delegation
Event bubbling means a click on a child element also fires on its parents, moving up from the element that was clicked. Event delegation uses this. You put one listener on the parent instead of one on every child. MDN's performance guide recommends it: fewer listeners to track means less work for the browser.
Delegation has a second benefit. Rows you add later need no setup, because the listener lives on the list, not on the rows.
elements.list.addEventListener('click', (event) => {
const item = event.target.closest('.todo-item');
if (!item) return;
if (event.target.closest('.delete-btn')) {
deleteTodo(item.dataset.id);
return;
}
if (event.target.matches('.todo-checkbox')) {
toggleComplete(item.dataset.id);
}
});
event.target is the element that was actually clicked. That might be an icon inside the delete button, not the button itself. closest() checks the element and then its parents until one matches the selector, and returns null if none does. So closest('.delete-btn') still finds the button when the click lands on the icon.
Delegation only works for events that bubble. MDN notes that focus and mouseenter don't bubble, and neither do blur and mouseleave. To delegate focus handling, listen for focusin and focusout, which do bubble.
4. Link elements to state with data attributes
Keep your data in a JavaScript array, not in the DOM. The DOM only shows that data. To know which array entry a row belongs to, store the entry's id in a data-* attribute. In JavaScript you read and write it through element.dataset.
function createTodoElement(todo) {
const li = document.createElement('li');
li.className = 'todo-item';
li.dataset.id = todo.id; // becomes data-id="…"
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.className = 'todo-checkbox';
checkbox.checked = todo.completed;
const text = document.createElement('span');
text.textContent = todo.text; // plain text: never parsed as HTML
const deleteButton = document.createElement('button');
deleteButton.type = 'button';
deleteButton.className = 'delete-btn';
deleteButton.textContent = 'Delete';
li.append(checkbox, text, deleteButton);
return li;
}
One detail trips people up. MDN notes that a dataset value is always converted to a string. If your ids are numbers, item.dataset.id === todo.id is never true. This app stores ids as strings from the start, so the comparisons below just work.
5. Keep user input out of innerHTML
innerHTML parses a string as HTML. MDN calls it probably the most common route for cross-site scripting (XSS). It blocks injected <script> tags, but attackers have many other ways in. A to-do item such as <img src=x onerror=alert(1)> would run code as soon as the broken image fails to load.
// Risky: the input is parsed as HTML
li.innerHTML = elements.input.value;
// Safe: the input is shown as plain text
li.textContent = elements.input.value;
| Method | What it does | XSS risk with user input | When to use |
|---|---|---|---|
innerHTML |
Parses a string as HTML | High | Fixed markup you wrote yourself |
textContent |
Sets plain text, nothing is parsed | None | Any user-supplied text |
createElement() |
Builds nodes one by one | None, if text goes in with textContent |
Structured rows such as list items |
If you really need HTML from users, run it through a maintained sanitizer such as DOMPurify first. As a rule of thumb, don't write your own filter with regular expressions.
6. Put it together
Split the code into state functions and UI functions. State functions change the array. UI functions change the DOM. Each one does one job.
const state = { todos: [] };
let nextId = 1;
const ui = {
appendItem(todo) {
elements.list.append(createTodoElement(todo));
},
removeElement(id) {
const el = elements.list.querySelector(`[data-id="${id}"]`);
if (el) el.remove();
},
};
function addTodo(text) {
const todo = { id: String(nextId++), text, completed: false };
state.todos.push(todo);
ui.appendItem(todo);
}
function deleteTodo(id) {
state.todos = state.todos.filter((todo) => todo.id !== id);
ui.removeElement(id);
}
function toggleComplete(id) {
const todo = state.todos.find((t) => t.id === id);
if (todo) todo.completed = !todo.completed;
}
elements.form.addEventListener('submit', (event) => {
event.preventDefault();
const text = elements.input.value.trim();
if (!text) return;
addTodo(text);
elements.input.value = '';
});
const initialTodos = ['Write the spec', 'Build the form', 'Test on a phone'].map(
(text) => ({ id: String(nextId++), text, completed: false })
);
state.todos.push(...initialTodos);
renderBatch(initialTodos);
The earlier version used Date.now() for ids. Two items added in the same millisecond would get the same id, and the number never matched the string from dataset. A counter stored as a string avoids both problems. If items come from a server, use the server's ids instead.
Load the script at the end of the <body>, or with defer, so the elements exist before the lookups in section 1 run.
Fixed in this version
The earlier code built rows with innerHTML and a sanitize() function that was never defined; it now uses createElement() and textContent. Rows lacked the todo-item class the click handler needs, and matches('.delete-btn') missed clicks on an icon inside the button; both now work through closest().
When to skip the framework
You don't need to pick a side. A framework earns its place when many parts of the page depend on shared state. For a small widget, a browser extension popup or a form with one dynamic list, plain DOM code like the code above is often enough. It also helps you debug the framework code you already write.
Next in the series, prototypes and ES6 classes shows how the objects behind elements and ui work.
Frequently asked questions
Is DocumentFragment faster than appending elements one by one?
Not by much, and sometimes not at all. MDN says its performance benefit is often overstated and that readability should come first. Use it to keep one clear insertion point, and avoid mixing layout reads with writes.
Why use event delegation instead of a listener on each item?
One listener on the parent handles every child, including children added later. MDN's performance guide notes that fewer listeners means less for the browser to track. You also skip adding and removing listeners each time a row changes.
What is the difference between matches() and closest()?
matches() tells you whether one element fits a selector. closest() checks the element and then each parent, and returns the first match or null. In a delegated handler, closest() copes with clicks on icons or text inside a button.
Is innerHTML always unsafe?
No. It is fine for fixed HTML that you wrote yourself. It is unsafe when any part of the string comes from users, URLs or other outside data. For that text, use textContent, or build nodes with createElement().
Why does dataset return a string when I stored a number?
Data attributes are HTML attributes, and attribute values are strings. MDN notes that any value you set through dataset is converted to a string. Store ids as strings, or convert them before you compare.
Sources
Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.
- MDN: DocumentFragment
- MDN: JavaScript performance optimization
- MDN: Reflow (glossary)
- web.dev: Avoid large, complex layouts and layout thrashing
- MDN: Event bubbling
- MDN: Element focusin event
- MDN: Element mouseenter event
- MDN: Element.closest()
- MDN: HTMLElement.dataset
- MDN: Element.innerHTML (security considerations)
- DOMPurify README
- MDN: Document.querySelector()
All 30 parts in this series
- Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
- Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
- Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
- Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
- Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
- Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
- Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
- Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
- Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
- Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
- Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
- Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
- Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
- Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
- Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
- Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
- Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
- Part 18Getting Started with React: Deconstructing JSX and Component Architecture
- Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
- Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
- Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
- Part 22React Architecture: Advanced Navigation and Data Flow Patterns
- Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
- Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
- Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
- Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
- Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
- Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
- Part 29Introduction to Micro Frontends: Building Scalable Architectures
- Part 30The Frontend Architecture: From Junior Developer to Tech Lead



Comments
Loading comments...