JavaScript DOM Interview Questions
Last updated 2026-11-19
DOM questions are staples of front-end interviews because they connect the language to the browser. Expect to explain how events propagate, why event delegation helps, how to create and update elements safely, and what causes layout thrashing.
The answers below cover selection, events, safe rendering, script loading, storage and the observer APIs, with examples that can be pasted into a browser console. Where behaviour differs between browsers, the standard behaviour is described.
| Level | Fresher to 3 years |
|---|---|
| Focus | Selection, events, rendering, browser APIs |
| Runtime | Modern browsers |
What interviewers care about
Show that you understand the cost of DOM operations and the security angle. Reading layout properties right after writing styles forces reflow, and inserting user text as HTML opens cross-site scripting holes.
- Batch DOM writes and avoid interleaving reads and writes
- Use textContent for untrusted text
- Use event delegation for lists of items
Related topics
Event timing details are in the event loop, handler context in the this keyword, and component-level concerns in React interview questions. For the full round format see how to crack a frontend interview.
JavaScript DOM Interview Questions: questions with worked answers
1 What is the DOM?
easyThe Document Object Model is the browser's in-memory tree representation of an HTML document, exposed to JavaScript as objects. Elements, text and comments are nodes, and the API lets scripts read and change structure, content and style, and react to events. It is not part of the JavaScript language but a web platform API, available as the document object.
2 What is the difference between getElementById, querySelector and querySelectorAll?
easygetElementById finds one element by id and is the fastest. querySelector accepts any CSS selector and returns the first match or null. querySelectorAll returns a static NodeList of all matches. getElementsByClassName and getElementsByTagName return live HTMLCollections that update as the DOM changes, while querySelectorAll results do not.
javascriptconst first = document.querySelector(".item"); const all = document.querySelectorAll("ul > li"); console.log(all.length); const live = document.getElementsByClassName("item"); // live collection document.body.append(Object.assign(document.createElement("div"), { className: "item" })); console.log(live.length); // increased by one automatically3 Explain event bubbling and capturing.
mediumWhen an event occurs, it travels in three phases: capturing from the window down to the target, the target phase, and bubbling back up to the window. Listeners run in the bubbling phase by default, and the third argument true or the option capture: true registers one for the capturing phase. Some events, such as focus and blur, do not bubble, but have bubbling counterparts focusin and focusout.
javascript// <div id="outer"><button id="btn">Go</button></div> outer.addEventListener("click", () => console.log("outer bubble")); outer.addEventListener("click", () => console.log("outer capture"), true); btn.addEventListener("click", () => console.log("button")); // click on button prints: outer capture, button, outer bubble4 What is event delegation and why use it?
mediumInstead of attaching a listener to every child, attach one to a common ancestor and use event.target, or closest, to find which child was clicked. It uses less memory, and it works for elements added later. Use closest to handle clicks on nested content inside the item.
javascriptconst list = document.querySelector("#todos"); list.addEventListener("click", (e) => { const li = e.target.closest("li"); if (!li || !list.contains(li)) return; li.classList.toggle("done"); });5 What is the difference between event.target and event.currentTarget?
mediumtarget is the element that originally triggered the event, the deepest one clicked. currentTarget is the element whose listener is currently running, which is the one you attached it to. In a delegated handler they usually differ. In an arrow function handler, use currentTarget instead of this.
6 What is the difference between preventDefault and stopPropagation?
mediumpreventDefault cancels the browser's default action for the event, such as following a link or submitting a form, but the event still propagates. stopPropagation stops the event from reaching ancestor listeners, but does not cancel the default action. stopImmediatePropagation also stops other listeners on the same element.
javascriptform.addEventListener("submit", (e) => { e.preventDefault(); // don't reload the page const data = new FormData(form); console.log(Object.fromEntries(data)); });7 What is the difference between innerHTML, textContent and innerText, and what is the security issue?
mediumtextContent sets or reads raw text, is fast and never parses markup. innerText is aware of CSS and visibility, so reading it triggers layout. innerHTML parses a string as HTML, so assigning untrusted input lets an attacker inject scripts through attributes such as onerror, which is cross-site scripting. Use textContent, create elements with the DOM API, or sanitise with a trusted library.
javascriptconst el = document.querySelector("#out"); const input = '<img src=x onerror="alert(1)">'; el.innerHTML = input; // dangerous: runs the handler el.textContent = input; // safe: shown as text8 How do you create and insert elements efficiently?
mediumCreate nodes with createElement, set properties, and insert with append, prepend, before, after or insertAdjacentElement. For many items, build them into a DocumentFragment or a detached parent first and insert once, so the browser does one layout instead of many. Replacing large parts with innerHTML is acceptable for trusted markup but loses event listeners on replaced nodes.
javascriptconst frag = document.createDocumentFragment(); for (let i = 1; i <= 100; i++) { const li = document.createElement("li"); li.textContent = `Item ${i}`; frag.append(li); } document.querySelector("ul").append(frag); // one insertion9 What are reflow and repaint, and what is layout thrashing?
hardReflow, or layout, recomputes element sizes and positions and is triggered by changes to geometry such as width, content or fonts. Repaint redraws pixels after visual changes like colour. Reflow always implies repaint and is more expensive. Layout thrashing happens when code alternates between writing styles and reading layout values such as offsetHeight in a loop, forcing a synchronous reflow each time. Batch all reads first, then all writes, or use requestAnimationFrame, and prefer transform and opacity for animation.
javascript// slow: forces layout on every iteration items.forEach((el) => { el.style.width = el.offsetWidth + 10 + "px"; }); // better: read all, then write all const widths = items.map((el) => el.offsetWidth); items.forEach((el, i) => { el.style.width = widths[i] + 10 + "px"; });10 What is the difference between DOMContentLoaded and load, and between defer and async?
mediumDOMContentLoaded fires when the HTML has been parsed and deferred scripts have run, without waiting for images and styles. load fires when the whole page and its resources are finished. A normal script blocks parsing. defer downloads in parallel and runs after parsing in order. async downloads in parallel and runs as soon as it arrives, in no guaranteed order, which suits independent scripts such as analytics.
11 Compare localStorage, sessionStorage and cookies.
mediumlocalStorage keeps strings per origin until cleared, with a typical limit of about 5 MB, and is shared across tabs. sessionStorage is the same API but scoped to one tab and cleared when it closes. Cookies are small, up to about 4 KB, are sent with every matching HTTP request, can expire, and can be marked HttpOnly, Secure and SameSite for protection. Never store secrets such as tokens in localStorage where scripts can read them if you can use HttpOnly cookies.
javascriptlocalStorage.setItem("user", JSON.stringify({ id: 1 })); const u = JSON.parse(localStorage.getItem("user") ?? "null"); console.log(u.id); // 112 How does IntersectionObserver help, for example with lazy loading?
mediumIntersectionObserver notifies you asynchronously when an element enters or leaves the viewport or another element, without scroll listeners that run on every event. It is used for lazy-loading images, infinite scroll and analytics. Call unobserve after loading to avoid repeat work.
javascriptconst io = new IntersectionObserver((entries) => { for (const e of entries) { if (e.isIntersecting) { e.target.src = e.target.dataset.src; io.unobserve(e.target); } } }, { rootMargin: "200px" }); document.querySelectorAll("img[data-src]").forEach((img) => io.observe(img));13 What are the passive and once options for addEventListener?
mediumonce: true removes the listener after its first call. passive: true promises the handler will not call preventDefault, so the browser can scroll immediately without waiting for it, improving touch and wheel performance. Touch and wheel listeners on window and document are passive by default in modern browsers. signal lets an AbortController remove several listeners at once.
javascriptconst ac = new AbortController(); window.addEventListener("scroll", onScroll, { passive: true, signal: ac.signal }); btn.addEventListener("click", init, { once: true }); // later: ac.abort(); // removes the scroll listener14 What is the virtual DOM, and how does it differ from the real DOM and from Shadow DOM?
hardThe real DOM is the browser's tree of nodes. The virtual DOM is a lightweight JavaScript object tree used by libraries such as React to describe the desired UI. On change they compare the new tree with the previous one and apply only the differences to the real DOM, which keeps updates predictable. Shadow DOM is something else: a browser feature that gives a custom element its own encapsulated subtree and styles, hidden from the main document's selectors.
Frequently asked questions
What is the difference between a node and an element?
Node is the general type for everything in the tree, including text and comments. An element is a node that represents an HTML tag. childNodes includes text nodes, while children contains only elements.
Why does my event listener not work on dynamically added elements?
Listeners attach to existing elements only. Use event delegation on a stable ancestor, or attach the listener when you create each element.
What does document.ready mean in plain JavaScript?
There is no such property. Use the DOMContentLoaded event, or place the script at the end of the body or use defer.
How do I stop memory leaks with the DOM?
Remove listeners you no longer need, do not keep references to removed nodes in long-lived variables, and clear timers and observers when a component is destroyed.
Related guides
More in Programming Language Interview Questions by Language
- JavaScript ES6 Interview Questions
- JavaScript Event Loop Interview Questions
- JavaScript Hoisting and Scope Interview Questions
- JavaScript Interview Questions and Answers
- JavaScript Promises and Async/Await Interview Questions
- JavaScript Prototypes and Inheritance Interview Questions
- JavaScript this Keyword Interview Questions
- JVM Internals Interview Questions
- MySQL Interview Questions and Answers
- Nth Highest Salary in SQL: Interview Questions
- PL/SQL Interview Questions and Answers
- PostgreSQL Interview Questions and Answers