Document Object Model (DOM) Manipulation: Events, Selection, and Dynamic Rendering
The Document Object Model (DOM) is an object-oriented representation of the webpage, allowing scripts to update content, structure, and styles in real time. Manipulating the DOM efficiently is essential for smooth user experiences, animations, and responsive interactions.
Understanding the DOM Hierarchy
When an HTML document is parsed by the browser, every tag becomes an element node, attributes become attribute nodes, and text becomes text nodes. These nodes form an inverted tree starting from the `document` root object.
Selecting Nodes: querySelector vs getElementById
`document.querySelector()` and `document.querySelectorAll()` accept any valid CSS selector string, offering maximum flexibility.
`document.getElementById()` offers optimized lookup speed when querying known unique element identifiers.
// Single element match
const primaryNav = document.querySelector("#primary-navigation");
// NodeList of all article cards
const cards = document.querySelectorAll(".article-card");
cards.forEach(card => {
card.classList.add("interactive-focus");
});Modifying Content, Attributes, and Classes
Prefer `textContent` over `innerHTML` when inserting text to protect against Cross-Site Scripting (XSS) vulnerabilities.
Use the `classList` API (`add()`, `remove()`, `toggle()`, `contains()`) to manipulate styling cleanly via CSS classes rather than setting inline styles directly.
const menuButton = document.querySelector("#menu-toggle");
const mobileDrawer = document.querySelector("#mobile-drawer");
menuButton.addEventListener("click", () => {
const isExpanded = menuButton.getAttribute("aria-expanded") === "true";
menuButton.setAttribute("aria-expanded", String(!isExpanded));
mobileDrawer.classList.toggle("open");
});Event Bubbling and Event Delegation
Events propagate up the DOM tree from child to parent (event bubbling). Event delegation takes advantage of this by attaching a single event listener to a common ancestor instead of hundreds of listeners to individual child items.
This pattern conserves browser memory and automatically supports dynamically added child elements.
Memory Efficiency
Event delegation is crucial in search lists or data tables where items are dynamically filtered and re-rendered frequently.
Performance: Avoiding Layout Thrashing
Interleaving DOM reads (such as `offsetWidth`) with DOM writes (such as `style.width = '100px'`) forces the browser to synchronously recalculate layout repeatedly, causing stutter and frame drops.
Batch your DOM updates or use `DocumentFragment` when inserting multiple elements.