Browser & DOM
DOM Fundamentals
What is the DOM?
The DOM (Document Object Model) is a programming interface for HTML documents. It represents the page as a tree of nodes/objects that JavaScript can manipulate.
The DOM is not the HTML source code—it's the live, parsed representation that can be modified.
What problems does this solve?
- Establishes the fundamental difference between static HTML source code and the live, mutable object-oriented tree representation in memory.
What is the difference between document and window?
window: The global object representing the browser window. Containsdocument,location,history,localStorage, timers, etc.document: Represents the DOM. It's a property ofwindowand provides methods to access/manipulate HTML elements.
What problems does this solve?
- Clarifies the crucial boundary between the global browser context (window) and the parsed HTML document architecture (document).
What are the different types of DOM nodes?
| Node Type | Example | nodeType value |
|---|---|---|
| Element | <div>, <p> | 1 |
| Text | Text inside elements | 3 |
| Comment | <!-- comment --> | 8 |
| Document | document | 9 |
| DocumentFragment | Virtual container | 11 |
What problems does this solve?
- Differentiates between actual Element nodes, raw Text nodes, and Comment nodes during precise tree traversal.
4. What is the difference between innerHTML, innerText, and textContent?
innerHTML: Gets/sets HTML markup (parses HTML tags).textContent: Gets/sets all text content, including hidden elements. Doesn't trigger reflow.innerText: Gets/sets visible text only. Triggers reflow (slower).
Security: Never use innerHTML with user input (XSS risk).
5. What is the difference between getElementById, querySelector, and querySelectorAll?
| Method | Returns | Performance |
|---|---|---|
getElementById("id") | Single element | Fastest |
querySelector(".class") | First match | Fast |
querySelectorAll("div") | Static NodeList | Slower |
getElementsByClassName | Live HTMLCollection | Fast |
What is the difference between a NodeList and an HTMLCollection?
- NodeList: Can contain any node type.
querySelectorAllreturns a static NodeList (doesn't update). - HTMLCollection: Contains only elements.
getElementsByClassNamereturns a live collection (auto-updates).
What problems does this solve?
- Drastically optimizes memory and performance by securely batching massive DOM insertions off-screen entirely before a single live reflow.
How do you create and insert DOM elements?
What problems does this solve?
- Exposes the fundamental bidirectional event propagation architecture that drives the entire browser interaction model.
What is a DocumentFragment and why use it?
A lightweight container for DOM nodes that exists only in memory. When you append it to the DOM, only its children are inserted (the fragment itself disappears).
Benefit: Minimizes reflows when adding many elements.
What problems does this solve?
- Saves immense memory overhead by intelligently attaching a single event listener to a parent rather than thousands to individual children.
Events
What is Event Bubbling and Capturing?
Events propagate through the DOM in three phases:
- Capturing (Capture Phase): From
windowdown to the target. - Target Phase: Event reaches the target element.
- Bubbling Phase: From target back up to
window.
What problems does this solve?
- Crucially distinguishes between the hyper-specific nested element that physically triggered the click versus the parent element actually handling it.
What is Event Delegation?
Attaching a single event listener to a parent instead of multiple listeners on children. Uses bubbling to catch events from descendants.
Benefits: Better performance, works with dynamically added elements.
What problems does this solve?
- Provides absolute control over stopping event bubbling cascades and overriding native browser default behaviors (like form submissions).
What is the difference between e.target and e.currentTarget?
e.target: The element that triggered the event (where the click actually happened).e.currentTarget: The element the listener is attached to.
What problems does this solve?
- Surgically interrupts the execution of sibling event listeners attached to the exact same element during complex event collisions.
What do stopPropagation() and preventDefault() do?
e.stopPropagation(): Stops the event from bubbling up (or capturing down).e.preventDefault(): Prevents the browser's default action (e.g., form submit, link navigation).
What problems does this solve?
- Dramatically improves scrolling performance on mobile devices by explicitly promising the browser that `preventDefault()` will never be called.
What is stopImmediatePropagation()?
Stops propagation AND prevents other listeners on the same element from firing.
What problems does this solve?
- Evaluates the deep security, capacity, and lifecycle differences of native client-side storage mechanisms.
What are Passive Event Listeners?
Telling the browser that the listener will NOT call preventDefault(), allowing optimizations (especially for scroll/touch events).
Benefit: Smoother scrolling because browser doesn't wait to see if you'll prevent default.
What problems does this solve?
- Highlights the absolute foundational security perimeter that prevents malicious scripts from hijacking data across different domains.
Browser APIs
What is the difference between localStorage, sessionStorage, and cookies?
| Feature | localStorage | sessionStorage | Cookies |
|---|---|---|---|
| Capacity | ~5-10MB | ~5-10MB | ~4KB |
| Expiry | Never (manual) | Tab close | Configurable |
| Sent to server | No | No | Yes (every request) |
| Scope | Origin | Origin + Tab | Origin + Path |
What problems does this solve?
- Explains the explicit HTTP header handshake required to securely bypass the Same-Origin Policy for legitimate cross-origin API requests.
What is the Same-Origin Policy?
A security mechanism that restricts how scripts from one origin can interact with resources from another origin.
Same origin = Same protocol + domain + port
What problems does this solve?
- Demonstrates modern, promise-based asynchronous network requests over legacy, callback-heavy XMLHttpRequest pipelines.
What is CORS?
Cross-Origin Resource Sharing allows servers to specify which origins can access their resources.
The server sends headers like:
Preflight request: For "non-simple" requests (e.g., with custom headers), the browser first sends an OPTIONS request to check permissions.
What problems does this solve?
- Empowers modern Single Page Applications to seamlessly mutate the URL and navigate backward without ever triggering a hard page reload.
What is the Fetch API?
Modern way to make HTTP requests (replaces XMLHttpRequest).
Note:fetch only rejects on network errors, not HTTP errors (4xx/5xx). Check response.ok.
What problems does this solve?
- Provides a highly performant, scroll-event-free mechanism for infinitely loading lists and lazy-loading offscreen images.
What is the History API?
Allows manipulation of the browser's session history (back/forward navigation).
Used by SPAs for client-side routing without page reloads.
What problems does this solve?
- Allows utility scripts to deterministically react to physical changes in the DOM architecture without fragile polling loops.
What is the Intersection Observer API?
Asynchronously observes when elements enter or exit the viewport (or another element).
Use cases: Lazy loading images, infinite scroll, analytics tracking.
What problems does this solve?
- Enables highly responsive components that accurately react to their own physical dimension changes independently of the viewport width.
What is the MutationObserver API?
Watches for changes to the DOM tree.
Use cases: Detecting dynamic content changes, polyfilling features.
What problems does this solve?
- Exposes the exact, sequential choreography the browser executes to convert raw bytes into painted pixels on the screen.
What is the ResizeObserver API?
Observes changes to an element's size.
Use case: Responsive components that need to know their own dimensions.
What problems does this solve?
- Distinguishes between incredibly expensive geometrical recalculations (reflow) and relatively cheap visual updates (repaint).
Rendering & Performance
What is the Critical Rendering Path?
The sequence of steps to render a page:
- Parse HTML → Build DOM tree
- Parse CSS → Build CSSOM tree
- Combine → Render tree (visible elements only)
- Layout → Calculate positions/sizes
- Paint → Draw pixels
- Composite → Layer composition (GPU)
Blocking resources (CSS, sync JS) delay this process.
What problems does this solve?
- Prevents devastating performance bottlenecks caused by synchronously reading and writing DOM geometries in a tight loop.
What is the difference between Reflow and Repaint?
- Reflow (Layout): Recalculates element positions/sizes. Expensive. Triggered by changing dimensions, adding elements, resizing window.
- Repaint: Redraws pixels without layout change. Cheaper. Triggered by color, visibility, background changes.
What problems does this solve?
- Syncs complex JavaScript animations perfectly with the monitor’s physical refresh rate for buttery smooth UI transitions.
What is Layout Thrashing and how do you avoid it?
Repeatedly reading and writing to the DOM in a way that forces synchronous layout recalculations.
What problems does this solve?
- Provides absolute CSS encapsulation and DOM isolation, forming the indestructible foundation of modern Web Components.
What is requestAnimationFrame?
Schedules a function to run before the next repaint (~60fps). The correct way to do smooth animations.
Benefits: Syncs with display refresh rate, pauses when tab is hidden.
What problems does this solve?
- Clarifies the exact timeline difference between the HTML skeleton being parsed versus every heavy image and iframe finishing download.
What is the difference between setTimeout, setInterval, and requestAnimationFrame?
| Method | Use Case | Behavior |
|---|---|---|
setTimeout | Delay execution once | Runs after X ms (minimum) |
setInterval | Repeat at interval | Can drift/stack if callback is slow |
requestAnimationFrame | Visual animations | Syncs with display refresh (~16ms) |
What problems does this solve?
- Defines the core architectural difference between synchronous timer delays, background processing loops, and high-performance native rendering frames.
Advanced Topics
What is the Shadow DOM?
An encapsulated DOM tree attached to an element. Styles and scripts don't leak in or out.
Use cases: Web Components, style isolation, third-party widgets.
What problems does this solve?
- Provides absolute CSS encapsulation and DOM isolation, forming the indestructible foundation of modern Web Components.
What is the difference between load and DOMContentLoaded events?
DOMContentLoaded: Fires when HTML is parsed and DOM is ready (before images/stylesheets finish loading).load: Fires when the entire page (including all resources) has loaded.
Use DOMContentLoaded for DOM manipulation; load for image dimensions.
What problems does this solve?
- Clarifies the exact timeline difference between the HTML skeleton being parsed versus every heavy image and iframe finishing download.
What is requestIdleCallback?
Schedules low-priority work to run during browser idle periods.
Use cases: Analytics, prefetching, non-critical updates.
Note: Not supported in Safari; use setTimeout as fallback.
What problems does this solve?
- Schedules low-priority, non-essential background tasks explicitly during the browser’s microscopic moments of idle downtime.