JavaScript · Lesson 18 of 20 · 4 min
Working with the DOM
DOM questions test if you know how to avoid performance bottlenecks when the UI gets complex.
After this, you will be able to explain exactly why and how you'd optimize rendering a large list of elements, handling events on them, and animating them smoothly. This isn't about getElementById; it's about proving you understand the cost of browser rendering.
Avoid Layout Thrashing
Every time you change the DOM, you risk forcing the browser to recalculate the layout of the page (a reflow) and redraw pixels (a repaint). These are expensive operations, and doing them badly is the easiest way to create a janky, unresponsive UI.
The most common trap is layout thrashing. This happens when you alternate between reading layout-sensitive properties and writing to the DOM in a loop.
- Read: Accessing properties like
element.offsetHeight,element.scrollTop, or callingelement.getBoundingClientRect(). - Write: Changing styles, class names, or attributes that affect geometry or position.
When you read a property like offsetHeight after making a change, you force the browser to perform a synchronous reflow to give you an up-to-date value. Do this in a loop, and you're forcing dozens of reflows instead of one.
The interview question: "How would you optimize this code?"
function resizeAllParagraphs(paragraphs) { for (let p of paragraphs) { const width = p.parentElement.offsetWidth; // Read p.style.width = (width / 2) + 'px'; // Write } }Your answer: "This code causes layout thrashing. To fix it, you should batch the DOM reads and then batch the DOM writes. First, read all the parent widths into an array. Then, loop through that array and update the paragraph styles. This ensures the browser only has to reflow once."
Batch Updates with DocumentFragment
The single most important pattern for adding multiple elements to the DOM is to do it in one operation. Attaching elements one-by-one in a loop triggers a reflow for each appendChild call.
A DocumentFragment is a lightweight, in-memory DOM node container. You can build an entire subtree of elements within it, then append the fragment to the live DOM once. This results in a single reflow and repaint, no matter how many elements you added.
This is the standard, expected solution for rendering a list of data from an API.
function renderList(items, containerElement) {
// Clear any existing content
containerElement.innerHTML = '';
// 1. Create a fragment to hold the new nodes
const fragment = document.createDocumentFragment();
items.forEach(itemText => {
// 2. Create and configure nodes, but append them to the fragment
const li = document.createElement('li');
li.textContent = itemText;
li.className = 'list-item';
fragment.appendChild(li);
});
// 3. Append the entire fragment to the live DOM in a single operation
containerElement.appendChild(fragment);
}
// Usage:
const data = ['Item 1', 'Item 2', 'Item 3', '...many more'];
const listContainer = document.getElementById('my-list');
renderList(data, listContainer);
Handle Events on Hundreds of Elements
The trap: Attaching an event listener to every single row in a 1,000-item table. This is inefficient, consumes memory, and breaks when you add new rows dynamically.
The correct pattern is event delegation. You attach a single event listener to a common ancestor (like the <ul> or <table>). When an event occurs on a child, it "bubbles up" the DOM tree to the parent. The listener on the parent can then inspect event.target to determine which child was actually clicked.
Benefits are significant:
- Performance: One listener instead of thousands.
- Dynamic Content: Works automatically for elements added to the container later. No need to re-bind listeners.
- Simplicity: Centralized event handling logic.
Use
event.target.closest(selector)to reliably find the element you care about. If a user clicks an icon inside a button,event.targetwill be the icon.event.target.closest('button')will correctly find the button that contains the icon.
Synchronize Updates with requestAnimationFrame
For animations or frequent updates tied to user input like scrolling or resizing, you need to sync your DOM changes with the browser's rendering cycle. A 60fps refresh rate gives you about 16.7ms to do all your work for a single frame.
Using setTimeout or setInterval for animations is a bad practice. Their timing is not aligned with the browser's repaint schedule, which can lead to dropped frames and visual jank.
requestAnimationFrame(callback) (rAF) tells the browser you want to run callback right before the next repaint. This is the correct tool for the job. The browser can optimize, batching multiple rAF calls into a single repaint. It also automatically pauses when the tab is not visible, saving CPU and battery.
A common use case is debouncing a resize or scroll handler to prevent it from firing hundreds of times per second. Using rAF ensures your update logic runs at most once per frame.
Try it
Create an HTML file with an empty <ul>. Write a script that generates an array of 10,000 strings. Render them to the <ul> twice: first using a naive for loop with appendChild inside, and second using a DocumentFragment. Use performance.now() before and after each render function to measure and log the time difference.
Next: You'll apply these performance principles as we look at Advanced Array Methods & Data Structures.
Lock it in — apply this lesson under interview conditions.