DOM and Browser Events Interview Questions for Web Development
25 DOM and Browser Events questions with answers for web development roles — 8 easy, 12 medium, 5 hard.
About DOM and Browser Events
The DOM connects JavaScript to the page. You will revise selecting and creating elements, event bubbling and delegation, storage options, AJAX with fetch, reflow and repaint, and safe rendering of user data. Practical rounds often ask you to build a todo list, form validation, modal or infinite scroll without a framework.
Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
The Document Object Model is a tree representation of an HTML page that the browser builds after parsing. Each element, attribute and piece of text becomes a node that JavaScript can read and change through APIs like document.querySelector, element.classList and element.append. When the DOM changes, the browser updates what users see. The DOM is not the HTML source itself; scripts can change it after the page loads.
02
What is the difference between preventDefault and stopPropagation?
preventDefault stops the browser's default action for the event, such as a form submitting and reloading the page or a link navigating. stopPropagation stops the event from bubbling further to parent elements, but the default action still happens. They solve different problems and are sometimes used together. Overusing stopPropagation can break delegated listeners and analytics scripts that listen at the document level.
03
What is the difference between DOMContentLoaded and the load event?
DOMContentLoaded fires when the HTML has been fully parsed and the DOM is built, without waiting for images, stylesheets or iframes. load fires on window only after every resource, including images, has finished loading. Most scripts that attach listeners should run on DOMContentLoaded, or simply use defer. load is useful when you need image dimensions or must start something after everything is ready.
04
How is querySelector different from getElementById and getElementsByClassName?
querySelector and querySelectorAll accept any CSS selector and return the first match or a static NodeList. getElementById accepts only an id and is slightly faster. getElementsByClassName returns a live HTMLCollection that updates automatically when the DOM changes, which can cause surprises inside loops. In practice querySelector is used for flexibility, and the speed difference rarely matters.
AJAX means updating parts of a page by exchanging data with the server in the background, without a full page reload. Originally it used XMLHttpRequest and XML, but today it is done with the fetch API and JSON. Examples include live search suggestions, adding to cart without reload, and infinite scroll. The server returns data, and JavaScript updates the DOM with the result.
06
Build a todo list where items can be added and deleted using event delegation.
The listeners were attached with querySelectorAll when the page loaded, so they exist only on the buttons that were present at that moment. New buttons have no listener. The clean fix is event delegation: attach one listener to a stable parent and check event.target.closest('.btn'). Alternatively, attach the listener when creating each new element, but delegation scales better for large lists.
08
How would you explain a technical problem to a non-technical client?
Situation: a client asked why their site was slow on mobile. Task: I needed approval to optimise images, which meant extra work. Action: I avoided jargon, showed a side-by-side video of load times, and compared large images to sending a heavy parcel by post. Result: the client approved the work, load time dropped from 7 to 2.5 seconds, and they trusted my later suggestions more.
When an event fires, it travels in three phases: capturing from window down to the target, the target phase, and bubbling back up through ancestors. By default, addEventListener handles the bubbling phase, so a click on a button also triggers click handlers on its parent div and body. Passing { capture: true } runs the handler during the capturing phase. Some events like focus do not bubble, but focusin does.
Event delegation attaches one listener to a common parent instead of many listeners on child elements, then uses event.target.closest() to find which child was clicked. Because of bubbling, it works even for children added later. For example, one listener on a ul can handle delete buttons for hundreds of todo items. It saves memory and avoids re-binding listeners after dynamic updates.
11
What is the difference between innerHTML, textContent and innerText?
innerHTML reads or writes HTML markup, so inserting user input through it can run malicious scripts and cause XSS. textContent reads or writes raw text, including hidden elements, and is fast because it does not trigger layout. innerText returns only visible text as rendered, respects CSS, and triggers a reflow, so it is slower. For displaying user data, textContent is the safe default.
localStorage stores about 5 MB per origin and persists until cleared. sessionStorage has similar size but is cleared when the tab closes and is separate per tab. Cookies are small, around 4 KB, are sent to the server with every request, and can be HttpOnly, Secure and SameSite. Use cookies for session identifiers, and storage for UI preferences. Never store tokens or passwords in localStorage, since any XSS can read it.
13
What are custom events and when would you use them?
Custom events let components communicate without knowing about each other. You create one with new CustomEvent('cart:updated', { detail: { count: 3 }, bubbles: true }) and fire it with element.dispatchEvent. Any part of the page can listen with addEventListener('cart:updated'). For example, a product card can announce an add-to-cart action, and the header badge updates itself, keeping code loosely coupled.
14
Validate a signup form with JavaScript before submission.
Check fields on submit and show inline messages:
form.addEventListener('submit', (e) => {
const errors = [];
if (form.name.value.trim().length < 3) errors.push('Name too short');
if (!/^[6-9]\d{9}$/.test(form.mobile.value)) errors.push('Invalid mobile');
if (form.password.value !== form.confirm.value) errors.push('Passwords do not match');
if (errors.length) {
e.preventDefault();
errorBox.textContent = errors.join('. ');
}
});
Client validation improves experience, but the server must validate again.
15
Create a dark mode toggle that remembers the user's choice.
Store the choice in localStorage and apply it on load:
const root = document.documentElement;
const saved = localStorage.getItem('theme');
if (saved) root.dataset.theme = saved;
toggle.addEventListener('click', () => {
const next = root.dataset.theme === 'dark' ? 'light' : 'dark';
root.dataset.theme = next;
localStorage.setItem('theme', next);
toggle.setAttribute('aria-pressed', next === 'dark');
});
Running the first lines in a small inline script in the head avoids a flash of the wrong theme.
16
Fetch a list of products and render them safely into the page.
The dialog element handles focus and the Escape key for you:
<button id='open'>Enquire now</button>
<dialog id='enquiry'>
<form method='dialog'>
<p>Thank you for your interest.</p>
<button>Close</button>
</form>
</dialog>
<script>
const dlg = document.getElementById('enquiry');
document.getElementById('open').addEventListener('click', () => dlg.showModal());
</script>
showModal places it in the top layer with a backdrop, and form method='dialog' closes it without a request.
18
A comment section displays user input using innerHTML. What is the risk and fix?
It allows stored cross-site scripting: a user can post <img src=x onerror=...> and the script runs for every visitor, stealing sessions or defacing the page. I would switch to textContent or createElement for rendering, escape output on the server, and if rich text is needed, sanitise with a library like DOMPurify. A strict Content Security Policy adds another layer by blocking inline scripts.
19
Users lose a long form's data when they accidentally refresh. How do you solve it?
I would autosave the form into sessionStorage or localStorage on input with a small debounce, then restore values on page load and clear them after successful submission. A beforeunload warning can ask users to confirm leaving when there are unsaved changes. Sensitive fields like passwords or card details must never be saved. For multi-step forms, saving drafts on the server is more reliable.
20
Describe a time you improved the performance of a web page.
Situation: our product listing page took over 6 seconds to become interactive. Task: I was asked to bring it under 3 seconds. Action: I profiled it in DevTools, found a large unused library and unoptimised images, replaced the library with native code, converted images to WebP with lazy loading, and deferred third-party scripts. Result: interaction time dropped to about 2.4 seconds and bounce rate fell noticeably.
21
What is the difference between reflow and repaint?
Reflow, or layout, happens when the browser recalculates positions and sizes, triggered by changing width, adding elements, or reading offsetHeight after a write. Repaint happens when only visual styles like colour or background change. Reflow is more expensive and can cascade to the whole page. Animating transform and opacity avoids both because they are handled by the compositor, which keeps animations smooth at 60 frames per second.
22
Implement infinite scroll using IntersectionObserver.
Observe a sentinel element at the bottom of the list:
const sentinel = document.querySelector('#sentinel');
let page = 1, loading = false;
const observer = new IntersectionObserver(async ([entry]) => {
if (!entry.isIntersecting || loading) return;
loading = true;
const res = await fetch('/api/posts?page=' + (++page));
const posts = await res.json();
if (!posts.length) observer.disconnect();
posts.forEach(renderPost);
loading = false;
}, { rootMargin: '200px' });
observer.observe(sentinel);
It is far cheaper than listening to every scroll event.
23
The page stutters while scrolling because of a scroll event handler. How do you fix it?
Scroll events fire many times per second, so heavy work in the handler blocks the main thread. I would throttle the handler or batch DOM writes inside requestAnimationFrame, mark listeners as { passive: true }, and avoid reading layout properties like offsetTop after writing styles. For tasks like lazy loading, sticky effects or reveal animations, I would replace the handler with IntersectionObserver or CSS position: sticky.
24
Users click the Pay button twice and get charged twice. How do you prevent it?
On the front end, I would disable the button and show a loading state as soon as the first click is handled, and re-enable it only on error. But the real fix must be on the server: generate an idempotency key or order id per checkout, and reject or ignore a second request with the same key. Payment gateways support idempotent requests for exactly this reason.
25
Rendering a table with 5,000 rows freezes the browser. What are your options?
Creating thousands of nodes at once blocks the main thread. Options are server-side pagination, rendering in chunks with requestAnimationFrame, or virtual scrolling where only the 30 to 50 visible rows exist in the DOM at any time. I would also build rows in a DocumentFragment, avoid layout reads inside loops, and use CSS content-visibility: auto so off-screen rows skip rendering work.
Frequently asked questions
How important is DOM and Browser Events in Web Development interviews?
The DOM connects JavaScript to the page. You will revise selecting and creating elements, event bubbling and delegation, storage options, AJAX with fetch, reflow and repaint, and safe rendering of user data. Practical rounds often ask you to build a todo list, form validation, modal or infinite scroll without a framework.
How should I use the DOM and Browser Events sheet?
Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.