The Document Object Model (DOM)
The DOM is a programming interface for web documents. It represents the page as a structured tree of nodes, where each node is an object representing a part of the document (elements, text, comments). JavaScript acts as the language that interacts with this interface to create dynamic, interactive websites.
Selecting and Traversing Elements
Modern DOM manipulation favors querySelector and querySelectorAll, which allow selecting elements using standard CSS selectors.
const mainHeader = document.querySelector('#header-1');
const allButtons = document.querySelectorAll('.btn-action');
Traversal refers to moving between nodes in the tree: parentNode, children, nextElementSibling, etc. Accessing the DOM is computationally expensive, so traversal should be minimized.
The Event System
Events are the primary way users interact with the DOM. JavaScript uses an event-driven model.
Event Bubbling and Capturing
When an event occurs on an element, it doesn’t just trigger the listener on that element. It moves through phases:
- Capture Phase: From
windowdown to the target. - Target Phase: At the target element.
- Bubbling Phase: From the target back up to
window.
Event Delegation
Instead of attaching a listener to dozens of individual items (like list items in a large table), you can attach a single listener to a parent element. Because of bubbling, the parent can catch events from its children. You can then check event.target to see which child was actually clicked. This is a crucial optimization for memory and performance.
Event Prevention
const link = document.querySelector('a'); link.addEventListener('click', (event) => { // Stop the browser from navigating to the URL event.(); });
Reflow and Repaint: Performance Costs
Every time you modify the DOM, the browser may need to recalculate the positions and sizes of elements (Reflow) and then redraw them on the screen (Repaint).
Reflow is particularly expensive because a change to one element can trigger changes in its parent, children, and siblings.
Best Practices to Minimize Reflow:
- Batch DOM updates using
DocumentFragment. - Avoid reading layout properties (like
offsetHeight) in the same loop where you are writing style changes. - Use
requestAnimationFramefor animations to synchronize with the browser’s refresh rate.
Storage and Persistence
Browsers provide several APIs for persisting data on the client side:
- LocalStorage: Non-expiring, string-based storage (per domain).
- SessionStorage: Cleared when the tab is closed.
- IndexedDB: A low-level API for client-side storage of significant amounts of structured data, including files/blobs.
- Cookies: Small pieces of data sent with every HTTP request, primarily used for session management and tracking.