Top 30 DOM Interview Questions and Answers
30 multiple-choice questions on DOM, drawn from 30 bites out of the 64 tagged DOM on Tezvyn. Answer them here or read straight down. Every question carries the correct option, why it is correct, and a link to the bite it came from.
30 questions. Pick an answer, or open “Show the answer” to read it.
Answers are graded in your browser. Nothing is saved, and no XP or streak is earned here. The app keeps score.
Question 1 of 30
Why do properties like width, margin, and padding typically not inherit in CSS?
Show the answer
Answer: a · Because inheriting them would often lead to broken layouts and unusable pages.
The card explicitly states that properties like width, height, padding, margin, and border do not inherit because it would usually be undesirable, leading to unusable pages. The other options present plausible but incorrect reasons not mentioned in the card.
Question 2 of 30
Why would wrapping two table cells in a Fragment be preferable to wrapping them in a div?
Show the answer
Answer: a · Fragments avoid creating an invalid HTML structure since they do not add an extra DOM node.
A div placed directly inside a table row creates invalid HTML, while a Fragment groups children without introducing any DOM node. Claiming a performance benefit is a common misconception; the primary reason to use Fragments is structural and semantic correctness, not optimization.
Read the full bite: What is a React Fragment and why use it over a div?
Question 3 of 30
Which approach best implements click tracking for dozens of headlines and CTAs while remaining performant and maintainable?
Show the answer
Answer: b · Use a single delegated listener on a parent container, read data attributes to identify elements, and send via navigator.sendBeacon
Event delegation on a common ancestor avoids the performance cost of dozens of individual listeners and naturally handles dynamic content, while data attributes provide stable identifiers unlike brittle innerText or class names. The most tempting distractor, attaching unique listeners to every element, scales poorly and misses the efficiency and dynamic-content benefits that delegation provides.
Read the full bite: How would you track clicks on headlines and calls-to-action?
Question 4 of 30
During a normal page navigation in the same browser tab, which object is replaced while the other persists?
Show the answer
Answer: b · Only the document object is replaced; the window object persists as the tab container.
The window object represents the browser tab and global execution context, so it persists across navigation, while the document is the in-memory DOM representation of a specific page and is rebuilt. Claiming both are replaced is a common misconception that treats window and document as the same page-level entity rather than as container versus content.
Read the full bite: What is the fundamental difference between window and document?
Question 5 of 30
Which accurately describes the return values of getElementById and getElementsByClassName?
Show the answer
Answer: c · The first returns an Element or null; the second returns a live HTMLCollection.
getElementById returns a single Element or null, while getElementsByClassName returns a live HTMLCollection that automatically reflects DOM mutations. Option D is tempting because both methods query the DOM, but getElementById never returns a collection.
Read the full bite: How do you select by ID and class, and what is returned?
Question 6 of 30
When initializing UI handlers on a page with external images, which distinction between DOMContentLoaded and window.load matters most?
Show the answer
Answer: d · DOMContentLoaded fires after deferred scripts run but does not wait for images, letting handlers bind earlier
DOMContentLoaded fires after HTML parsing and deferred scripts complete, so you can bind UI handlers before heavy assets like images finish, whereas window.load waits for all subresources. The most tempting distractor reverses the two events: window.load is the one that waits for every asset, not DOMContentLoaded.
Read the full bite: Describe the difference between DOMContentLoaded and window.load
Question 7 of 30
What is the main drawback of adding your own variables and functions directly to the window object?
Show the answer
Answer: b · It increases the risk of naming conflicts and makes your code fragile.
The card states that adding variables directly to the window object "makes your code fragile and can lead to conflicts with third-party scripts." This 'global scope pollution' is the primary concern, not memory, security, or module prevention.
Read the full bite: The `window` Object: Your Browser's Global Scope
Question 8 of 30
You add a click listener to a parent with addEventListener('click', fn, true). When does fn run relative to a child element's default listener if the child is clicked?
Show the answer
Answer: c · fn runs before the child listener during event capture
Passing true as the third argument registers the parent listener for the capture phase, which fires as the event travels downward from the root, so it executes before the child's bubble-phase listener. Option B describes the default behavior when the third argument is omitted or false, not capture.
Read the full bite: Explain DOM event capturing and bubbling with addEventListener
Question 9 of 30
After storing parent.childNodes in a variable, a developer appends a new child and sees the stored length increase without reassignment. What explains this?
Show the answer
Answer: d · The stored reference is a live NodeList, but querySelectorAll returns a static snapshot that would not update.
childNodes is a live NodeList that mutates in place, while querySelectorAll returns a static snapshot that never updates. A is tempting because many developers assume all NodeLists share the same binding behavior, but querySelectorAll specifically captures a point-in-time copy.
Read the full bite: What are the key differences between NodeList and HTMLCollection?
Question 10 of 30
Which task is NOT primarily handled by the `document` object in JavaScript?
Show the answer
Answer: d · Redirecting the browser to a different web address.
The `document` object is for interacting with the page's content and structure, such as modifying elements, creating new ones, or finding existing elements. Navigating to a new URL is a browser-level action handled by the `window.location` object, not the `document` object.
Question 11 of 30
When JavaScript modifies an element using the DOM, what is the immediate and primary outcome?
Show the answer
Answer: a · The browser's visual rendering of the webpage is updated for the user.
The DOM is the browser's live, in-memory model of the webpage, so changes made via JavaScript directly update what the user sees. These changes do not affect the original HTML file on the server, which remains unchanged.
Read the full bite: The DOM: Your HTML as a Live Object Tree
Question 12 of 30
You must measure a rendered DOM element and immediately adjust a modal to prevent visual flicker. Which choice is correct?
Show the answer
Answer: d · useLayoutEffect, because it runs synchronously after DOM mutations but before paint, letting you correct layout before it is visible
useLayoutEffect runs synchronously after React commits DOM changes but before the browser paints, so layout corrections happen before the user sees anything. Option C is tempting because it names the right hook but incorrectly claims it runs after paint, which would actually cause the flicker you are trying to prevent.
Read the full bite: When would you choose useLayoutEffect over useEffect?
Question 13 of 30
Which scenario best illustrates why direct DOM manipulation is often avoided in favor of frontend frameworks for UI updates?
Show the answer
Answer: a · When the application requires frequent and complex updates to many parts of the user interface.
The card explicitly states that direct, frequent DOM manipulation is computationally expensive due to browser reflows and repaints, making it unsuitable for complex applications with many state changes. Frameworks like React and Vue were developed to address this performance issue. Option B describes a simple, infrequent update where direct DOM manipulation is appropriate, not avoided.
Read the full bite: DOM Manipulation: Treating Your Webpage Like a Live Object
Question 14 of 30
What is a key consideration when using nextSibling for DOM traversal?
Show the answer
Answer: c · It can return a text node if whitespace exists between elements in the HTML.
The card explicitly states that nextSibling can return a text node (representing whitespace) if there is whitespace between elements in the HTML source, calling this a 'classic footgun.' Option A is a common misconception; nextSibling operates on all node types, not just element nodes.
Question 15 of 30
Which scenario best describes a primary use case for configuring an event listener to operate during the capturing phase?
Show the answer
Answer: a · To handle an event on a parent element before it reaches and is processed by its nested child elements.
The capturing phase allows an event listener on an ancestor element to intercept and handle an event as it travels down the DOM tree before it reaches the target element. Option D describes the bubbling phase's behavior relative to the target, not capturing.
Read the full bite: Event Bubbling vs. Capturing: The DOM's Two-Way Street
Question 16 of 30
What is the primary benefit of using Shadow DOM for styling components?
Show the answer
Answer: c · It guarantees that a component's internal styles will not be affected by or affect the main document's global CSS.
The card states Shadow DOM solves "style collisions" and acts as a "shield" where "CSS rules defined inside the Shadow DOM only apply within it, and with few exceptions, CSS rules from the main page don't apply to the elements inside the shadow tree." Option A is incorrect because the card notes that Shadow DOM "creates more friction than it solves" if you need easy external overrides.
Question 17 of 30
A sidebar card is toggled ten times a minute. Why prefer v-show over v-if?
Show the answer
Answer: d · v-show keeps the node mounted and preserves internal state
v-show keeps the element in the DOM and only flips CSS display, preserving internal state and avoiding costly mount cycles during frequent toggles. Distractor B is wrong because toggling display CSS describes v-show, whereas v-if actually removes the element from the DOM.
Read the full bite: How do you conditionally render Login/Logout with isLoggedIn in Vue or Angular?
Question 18 of 30
In Angular, binding [disabled]="isDisabled" on a button sets the DOM property. Why must ARIA roles use [attr.role] instead of [role]?
Show the answer
Answer: d · The role HTML attribute has no corresponding DOM property on standard elements, so Angular must write to the markup directly
Angular writes to DOM properties by default, so attribute binding is required when no corresponding DOM property exists, such as with ARIA role or SVG attributes. Option B is tempting because it suggests a framework optimization, but the distinction is about the binding target, not change detection efficiency.
Read the full bite: What's the difference between Angular property and attribute binding?
Question 19 of 30
Which sequence of checks is required to safely read .value from a getElementById result in TypeScript?
Show the answer
Answer: b · Verify the element is not null and confirm it is an HTMLInputElement before reading .value.
getElementById returns HTMLElement or null, so you must first guard against null and then narrow the type to HTMLInputElement because HTMLElement lacks the .value property. Option C is tempting because a null check feels sufficient, but TypeScript will still reject .value on the generic HTMLElement type.
Read the full bite: What is getElementById's return type and the check needed for .value?
Question 20 of 30
A button containing a nested span is clicked. If the listener is attached to the button, what is the event type and which property reliably references the button?
Show the answer
Answer: c · It is a MouseEvent; use event.currentTarget to reference the button.
The click handler receives a MouseEvent, and event.currentTarget always refers to the element that owns the listener, whereas event.target points to the actual nested element clicked—such as the span—so it would fail to reference the button itself.
Read the full bite: What is the click event's type and how to reference the button?
Question 21 of 30
A Vue modal inside a transformed ancestor uses position: fixed yet fails to fill the viewport. What explains why Teleport fixes this?
Show the answer
Answer: b · It relocates the modal's markup to the body, escaping the ancestor's containing block and stacking context while keeping reactivity intact.
Teleport moves the markup to the body so the modal escapes the ancestor's transform-created containing block and stacking context, while its reactive state remains in the Vue tree. Distractor D is wrong because increasing z-index alone cannot escape a containing block, and Teleport explicitly changes the physical DOM location.
Read the full bite: In Vue 3, what problem does Teleport solve?
Question 22 of 30
Which technique validates at runtime that a querySelector result is specifically an HTMLInputElement?
Show the answer
Answer: c · Using an instanceof HTMLInputElement check before accessing input properties
Only instanceof performs runtime type validation. The generic querySelector<HTMLInputElement> approach is purely a compile-time contract and will not prevent errors if the selector actually matches a non-input element.
Read the full bite: Strategies to type querySelector results as HTMLInputElement
Question 23 of 30
Which sequence type-safely reads dataset.id from a clicked LI during event delegation when the LI contains nested children?
Show the answer
Answer: b · Cast event.target to HTMLElement, call closest('li'), verify instanceof HTMLLIElement, then read dataset.id
Option B is correct because event.target may be a nested child, so closest walks up to the LI and instanceof narrows the type safely before reading dataset.id. Option D is tempting but wrong because casting event.target directly to HTMLLIElement is unsafe and breaks when clicks land on nested elements.
Read the full bite: How do you type-safely check an LI click and read data-id?
Question 24 of 30
What is the main advantage of implementing a trackBy function with *ngFor in Angular?
Show the answer
Answer: d · It allows Angular to efficiently update the DOM by reusing elements instead of re-rendering them entirely.
The card explicitly states that trackBy prevents Angular from destroying and recreating the entire list in the DOM on every data update, instead allowing it to reuse existing elements. Option C is incorrect because trackBy primarily optimizes subsequent updates, not the initial rendering, and doesn't involve pre-caching.
Read the full bite: *ngFor trackBy: Smarter DOM Updates in Angular
Question 25 of 30
When creating a div in TypeScript and setting its plain text, which approach combines the precise DOM interface with the safest property assignment?
Show the answer
Answer: a · const div: HTMLDivElement = document.createElement('div'); div.textContent = 'Hello';
TypeScript overloads createElement('div') to return HTMLDivElement, and textContent is preferred over innerHTML for plain text to avoid XSS and unnecessary parsing. Option B is tempting because innerText looks equivalent, but it triggers style recalculation and differs in behavior, while Option D defeats TypeScript's type safety by using any.
Read the full bite: Programmatically create and append a div in TypeScript
Question 26 of 30
For which scenario would a Vue template ref be the most appropriate tool?
Show the answer
Answer: c · To programmatically set focus on an input field after the component mounts.
The card explicitly states that programmatic focus on an input is a canonical example and a key use case for template refs, as it requires direct DOM interaction. Option D describes the use of ref() for reactive data, which is distinct from using the ref attribute in the template to get a direct DOM element reference.
Read the full bite: Vue Template Refs: Reaching Past the Virtual DOM
Question 27 of 30
When appending 1,000 newly created elements in a loop, why does using a DocumentFragment improve performance over direct parent append?
Show the answer
Answer: c · It exists outside the active document tree, so appends do not trigger reflows or repaints
C is correct because a DocumentFragment lives outside the active document tree, so batch appends inside a loop cause zero reflows until the single final insertion. A is a tempting distractor because beginners often wrongly assume fragments reduce memory usage, but they actually minimize layout calculations.
Read the full bite: How would you use DocumentFragment to optimize adding 1,000 list items?
Question 28 of 30
Which pattern correctly implements an IntersectionObserver callback in TypeScript for lazy-loading images while preserving type safety and memory efficiency?
Show the answer
Answer: a · Type entries as IntersectionObserverEntry[], narrow entry.target with instanceof HTMLImageElement, and call observer.unobserve(entry.target) after setting src
The callback receives IntersectionObserverEntry[], and because entry.target is typed as Element, you must narrow it to HTMLImageElement before setting src and then call observer.unobserve(entry.target) to release that node. Option C is tempting because the array type is correct, but HTMLElement is still too broad for src and disconnect stops all observations instead of just the loaded image.
Read the full bite: Implement IntersectionObserver in TypeScript for lazy-loading images
Question 29 of 30
When building a single TypeScript handler for mixed form inputs, which strategy correctly preserves type safety when extracting values from checkboxes, text inputs, and selects?
Show the answer
Answer: b · Narrow event.target with instanceof checks and branch on element.type to read .checked or .value.
Narrowing with instanceof and branching on element.type lets the compiler verify you read .checked for checkboxes and .value for other elements. Option D is tempting because it uses a union type, but reading .value from a checkbox gives the string on rather than the boolean state, breaking both type safety and runtime logic.
Read the full bite: Write a generic TypeScript handler for mixed form inputs?
Question 30 of 30
When dynamically building a table of contents from article headings, which practice risks XSS if the heading text contains malicious markup?
Show the answer
Answer: d · Assembling the list with innerHTML instead of document.createElement
The card warns that innerHTML bypasses the DOM tree and risks XSS when heading text contains malicious markup, whereas createElement safely constructs nodes. Option B is wrong because scoping querySelectorAll to the article container is actually the recommended first step to avoid capturing header or footer headings.
Read the full bite: Build a dynamic table of contents from article h2 tags
Could you explain these out loud?
That is what an interview actually tests. Tezvyn gives you questions like these with what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.