Secure & Private (Zero Data Retention)
Free Access • No Sign-Up
DOM Manipulation
The Document Object Model (DOM) is a tree-like representation of your HTML that JavaScript can read and modify dynamically.
Try It Yourself
📋 Copy DOM Manipulation & DocumentFragment Snippet
// High-Performance DOM Querying & Mutation
const container = document.querySelector("#app");
// Document Fragment for Batch Insertion (Zero Reflows)
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const el = document.createElement("div");
el.className = "card";
el.textContent = `Card #${i}`;
fragment.appendChild(el);
}
container.appendChild(fragment);
⚠️ 5 Fatal Traps & JavaScript Pitfalls
Trap #1: Layout Thrashing from Interleaved Reads and Writes
Reading layout properties (like offsetHeight, clientWidth) immediately after modifying styles forces the browser engine to perform synchronous layout reflows on every loop cycle.
Trap #2: Cross-Site Scripting (XSS) via innerHTML
Injecting unescaped user input into innerHTML allows attackers to execute arbitrary malicious scripts. Always use textContent for raw text.
Trap #3: Querying Elements Before DOM is Ready
Running document.querySelector() before the HTML parser finishes returns null. Place scripts before </body> or listen for DOMContentLoaded.
Trap #4: Memory Leaks from Detached DOM Nodes
Removing an element from the DOM with el.remove() does not free its memory if JavaScript variables or event listeners still hold references to it.
Trap #5: NodeList vs. Array Confusion
querySelectorAll() returns a static NodeList, not an Array. While it supports forEach, it lacks map and filter in older browsers unless converted with Array.from().
💬 Frequently Asked Questions
Why is DocumentFragment faster for batch DOM updates?
A DocumentFragment exists in memory off the active DOM tree. Appending child elements to it triggers zero browser reflows; inserting the fragment into the live DOM performs a single repaint.
What is the difference between innerHTML, innerText, and textContent?
innerHTML parses and renders HTML tags; innerText considers CSS styling and triggers reflows; textContent retrieves or sets raw text without parsing HTML or triggering expensive reflows.
How does element.closest() work in DOM traversal?
closest(selector) traverses the element and its parents upward toward the document root, returning the first ancestor that matches the CSS selector.
What is the difference between querySelector and getElementById?
getElementById is specialized and slightly faster for ID lookups. querySelector is a universal selector supporting complex CSS rules, classes, attributes, and pseudo-selectors.
How do you safely toggle CSS classes on elements?
Use the classList API: el.classList.add(), el.classList.remove(), and el.classList.toggle("active", booleanCondition).