Javascript Interview Questions

JavaScript Interview Questions - DOM & Browser APIs

25 interview questions on DOM manipulation, event handling, event delegation, localStorage, sessionStorage, cookies, Fetch API, and browser storage APIs.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

25 interview questions on DOM manipulation, event handling, event delegation, localStorage, sessionStorage, cookies, Fetch API, and browser storage APIs. This interview-focused guide covers essential javascript interview questions - dom & browser apis concepts for technical interviews.

JavaScript Interview Questions – DOM & Browser APIs

DOM manipulation and browser APIs are essential for frontend developers. These 25 questions cover the DOM API, event handling, event delegation, browser storage, and modern web APIs.


1. What is the DOM?

The Document Object Model (DOM) is a tree-like representation of an HTML document. JavaScript can traverse and manipulate this tree to dynamically change content, structure, and styling.

const el = document.getElementById("myId");
el.textContent = "New text";
el.style.color = "red";
el.classList.add("active");

2. What are the ways to select DOM elements?

  • getElementById("id") — single element, fastest
  • querySelector(".class") — first match, CSS selector
  • querySelectorAll("div.class") — static NodeList
  • getElementsByClassName("class") — live HTMLCollection
  • getElementsByTagName("div") — live HTMLCollection

[!TIP] querySelectorAll returns a static NodeList. getElementsByClassName returns a live HTMLCollection that auto-updates.

3. What is the difference between innerHTML, textContent, and innerText?

  • innerHTML: Gets/sets HTML content (XSS risk)
  • textContent: Gets/sets all text including hidden elements (fast)
  • innerText: Gets only visible text, CSS-aware (slow, forces reflow)

4. What is event delegation?

Attaching a single event listener to a parent element to handle events on child elements via event bubbling. Handles dynamically added elements automatically.

document.getElementById("list").addEventListener("click", e => {
    if (e.target.matches(".delete-btn")) {
        e.target.closest("li").remove();
    }
});

5. What is event bubbling vs capturing?

Events propagate in 3 phases:

  1. Capturing: From window down to the target element
  2. Target: Event reaches the target
  3. Bubbling: From target back up to window
el.addEventListener("click", handler, false); // Bubbling (default)
el.addEventListener("click", handler, true);  // Capturing

6. What is preventDefault() vs stopPropagation()?

  • e.preventDefault() — prevents browser default behavior (form submit, link navigation)
  • e.stopPropagation() — stops event from bubbling up
  • e.stopImmediatePropagation() — also stops other listeners on same element

7. What is the difference between localStorage and sessionStorage?

  • localStorage: Persists across sessions and tabs (~5-10 MB)
  • sessionStorage: Cleared when tab is closed (~5-10 MB)
  • Both are per-origin, synchronous, string-only storage
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");

8. What are cookies?

Small text files (~4 KB) stored by the browser. Sent with every HTTP request to the domain. Used for sessions, authentication, tracking.

document.cookie = "user=Alice; max-age=3600; path=/";

9. What is the difference between localStorage and cookies?

FeaturelocalStorageCookies
Capacity~5-10 MB~4 KB
Sent to serverNoEvery request
ExpirationNeverSet manually
Accessible fromJavaScriptJavaScript + HTTP

10. What is the Fetch API?

Modern Promise-based interface for HTTP requests.

const res = await fetch("/api/data", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ key: "value" })
});
const data = await res.json();

11. How do you create and append DOM elements?

const div = document.createElement("div");
div.className = "box";
div.textContent = "Hello";
document.body.appendChild(div);

12. What is DocumentFragment?

A lightweight container for DOM nodes. Appending a fragment adds its children without the fragment itself. Efficient for batch DOM operations.

const fragment = document.createDocumentFragment();
items.forEach(item => {
    const li = document.createElement("li");
    li.textContent = item;
    fragment.appendChild(li);
});
list.appendChild(fragment); // Single reflow

13. What is IntersectionObserver?

Observes when an element enters/exits the viewport. Used for lazy loading, infinite scroll, analytics.

const observer = new IntersectionObserver(entries => {
    entries.forEach(e => {
        if (e.isIntersecting) e.target.classList.add("visible");
    });
});
observer.observe(document.querySelector(".target"));

14. What is MutationObserver?

Watches for DOM tree changes (child additions/removals, attribute changes).

15. What is ResizeObserver?

Reports changes to an element's dimensions. Better than window resize for responsive components.

16. What is the History API?

Manipulates browser session history: pushState(), replaceState(), popstate event. Foundation of SPAs routing.

17. What are data- attributes?

Custom HTML attributes prefixed with data-. Accessible via element.dataset.

<div data-user-id="123" data-role="admin">
const id = el.dataset.userId; // "123"

18. What is matches() on DOM elements?

Returns true if the element matches a CSS selector.

if (e.target.matches(".btn.delete")) { ... }

19. What is closest() on DOM elements?

Traverses up from the element (including itself) and returns the first ancestor matching a CSS selector.

e.target.closest("li"); // Find parent <li>

20. What is event handling and addEventListener()?

Registers an event handler without overwriting existing ones. Supports options: capture, once, passive.

el.addEventListener("click", handler, { once: true, passive: true });

[!TIP] passive: true tells the browser you won't call preventDefault(), enabling scroll performance optimizations.

21. What is removeEventListener()?

Removes a previously registered event listener. Requires the same function reference.

22. What is event propagation and how to stop it?

Event propagation is the process of events traveling through the DOM tree. Stop with stopPropagation() (bubbling) or stopImmediatePropagation().

23. What is a custom event?

Create and dispatch custom events using CustomEvent.

const event = new CustomEvent("userLogin", { detail: { userId: 123 } });
document.dispatchEvent(event);

24. What is the difference between window.onload and DOMContentLoaded?

  • DOMContentLoaded: Fires when HTML is parsed and DOM is ready (no waiting for images/CSS)
  • window.onload: Fires when ALL resources (images, stylesheets, scripts) are loaded

25. What is navigator object?

Provides browser and device information: navigator.userAgent, navigator.language, navigator.onLine, navigator.geolocation, navigator.clipboard.