Javascript DOM Interview Questions
Last Updated :
19 Sep, 2025
The JavaScript DOM (Document Object Model) is a programming interface that represents a web page as a tree-like structure, where every element (HTML tags, text, attributes) is an object that can be accessed and modified using JavaScript.
- Document Object:
document
is the root object to access the page. - Tree Structure: The HTML page is represented as nodes (elements, text, attributes).
- Manipulation: You can add, remove, or update elements, styles, and content.
- Events: DOM lets JavaScript respond to user actions (clicks, inputs, etc).
1. How is the DOM (Document Object Model) different from HTML?
HTML is the static code you write to define a webpage’s structure, while the DOM is the live, in-memory representation of that structure created by the browser.
- HTML exists in the file and shows the initial content.
- DOM is generated from HTML (and CSS, scripts, etc.) and can be modified dynamically by JavaScript.
- Changing the HTML file requires reloading the page, but updating the DOM can instantly reflect changes without a refresh.
2. What is the difference between DOM and BOM, and how do window
and document
relate?
JavaScript interacts with two key objects in the browser: DOM (Document Object Model) and BOM (Browser Object Model), but they serve different purposes.
DOM (Document Object Model) | BOM (Browser Object Model) |
---|
Represents the structure of a webpage (HTML and XML documents). | Represents the browser environment outside the page content. |
Allows access and manipulation of HTML elements, attributes, and content using the document object. | Provides objects and methods to control the browser, such as window , navigator , screen , location , and history . |
Example: document.getElementById("myDiv").textContent = "Hello" modifies page content. | Example: window.alert("Hello") shows a browser alert; window.location.href = "url" navigates to a new page. |
Part of the page, exists inside the browser window. | Part of the browser itself, not tied to a specific page content. |
3. How do you select elements in the DOM?
JavaScript provides several ways to select elements in the DOM, but they differ in how they search and return results.
- getElementById: Selects a single element by its unique
id
. Returns one element or null
. - getElementsByClassName: Selects all elements with a given class name. Returns an HTMLCollection (live).
- getElementsByTagName: Selects all elements with a given tag (like
div
, p
). Returns an HTMLCollection (live). - querySelector: Selects the first matching element using a CSS selector (e.g.,
#id
, .class
, div p
). - querySelectorAll: Selects all matching elements using a CSS selector and returns a static NodeList.
HTML
<!DOCTYPE html>
<html>
<head>
<title>DOM Selection Example</title>
</head>
<body>
<h1 id="title">Hello World</h1>
<p class="text">First paragraph</p>
<p class="text">Second paragraph</p>
<div>Some content</div>
<div>Another content</div>
<script>
// getElementById
const title = document.getElementById("title");
console.log(title.textContent); // Output: Hello World
// getElementsByClassName
const paragraphs = document.getElementsByClassName("text");
console.log(paragraphs[0].textContent); // Output: First paragraph
console.log(paragraphs[1].textContent); // Output: Second paragraph
// getElementsByTagName
const divs = document.getElementsByTagName("div");
console.log(divs.length); // Output: 2
// querySelector
const firstPara = document.querySelector(".text");
console.log(firstPara.textContent); // Output: First paragraph
// querySelectorAll
const allParas = document.querySelectorAll(".text");
allParas.forEach(p => console.log(p.textContent));
// Output:
// First paragraph
// Second paragraph
</script>
</body>
</html>
4. What’s the difference between NodeList and HTMLCollection
JavaScript provides two array-like objects for accessing groups of DOM elements: NodeList and HTMLCollection, but they differ in how they are created, what they contain, and how they update.
- NodeList: Returned by methods like
querySelectorAll
. It can contain different node types (elements, text nodes, comments). A NodeList
can be static (doesn’t update automatically when the DOM changes) or live in some cases (like childNodes
). It supports iteration with forEach
. - HTMLCollection: Returned by methods like
getElementsByTagName
or getElementsByClassName
. It contains only element nodes, not text or comment nodes. It is always live, meaning it updates automatically when the DOM changes.
5. How do you create and append a new element dynamically?
JavaScript allows you to create and append new elements dynamically using the Document Object Model (DOM) methods.
- document.createElement(): Creates a new element node of the specified type (e.g.,
div
, p
, button
). - element.textContent / innerHTML: Lets you add text or HTML content inside the newly created element.
- parent.appendChild() / parent.append(): Appends the new element to a parent node in the DOM, making it visible on the page.
6. Difference Between innerHTML
vs innerText
vs textContent
?
JavaScript provides three ways to get or set the content of DOM elements: innerHTML, innerText, and textContent, but they differ in what they return, how they handle formatting, and performance.
innerHTML | innerText | textContent |
---|
Returns/sets the HTML markup inside an element. | Returns/sets the visible text only (respects CSS, ignores hidden text). | Returns/sets the all text content (includes hidden text). |
Parses and can insert HTML tags. | Only plain text, no HTML parsing. | Only plain text, no HTML parsing. |
More powerful but can be unsafe (XSS risk if inserting user input). | Safer but slower (forces reflow to calculate visible text). | Fastest (direct text node access). |
Example: <div><b>Hi</b></div> → " <b>Hi</b> " | "Hi" (ignores <b> ) | "Hi" (includes all text regardless of style). |
7. How does the Virtual DOM (e.g., React) differ from the real DOM?
JavaScript applications interact with two concepts: the Real DOM and the Virtual DOM, but they differ in performance, update mechanism, and efficiency.
Real / Actual DOM | Virtual DOM |
---|
Browser’s in-memory tree representation of HTML and CSS. | A lightweight JavaScript object that mimics the DOM. |
Directly updates the UI when changes are made. | Calculates differences (diffing) and updates only what changed in the Real DOM. |
Slow if frequent updates (each change triggers reflow/repaint). | Faster because updates are batched and minimized. |
Provided by browsers, works with plain JavaScript. | Implemented by libraries/frameworks (React, Vue, etc.). |
Changing the DOM can block rendering and affect performance. | Optimizes rendering : reduces blocking and improves performance. |
8. Explain event delegation?
JavaScript provides a way to handle events efficiently using event delegation, which takes advantage of event bubbling to manage multiple child elements with a single event listener on their parent.
Instead of attaching event listeners to every child element, you attach one to a common parent. When an event occurs, it bubbles up to the parent, where you can check the event’s target and handle it accordingly.
Example:
Suppose you have a list of items that can be clicked:
JavaScript
document.getElementById("list").addEventListener("click", function(event) {
if (event.target.tagName === "LI") {
console.log("You clicked:", event.target.textContent);
}
});
9. What is the differnce between addEventListener
vs setting onclick
JavaScript provides two ways to attach events: addEventListener and setting onclick, but they differ in flexibility, multiple handlers, and control.
- onclick: Assigns an event handler directly to an element’s
onclick
property. It supports only one handler at a time if you set another, it overwrites the previous one. - addEventListener: Allows attaching multiple handlers for the same event on the same element, does not overwrite existing handlers, and gives extra control with options like
capture
, once
, and passive
.
10. How do you prevent default behavior for an event?
JavaScript allows you to control how events behave in the browser, and sometimes you need to stop their built-in (default) actions.
- Default behavior: Many events have automatic actions, like clicking a link navigating to another page, or submitting a form refreshing the page.
- preventDefault(): You can call
event.preventDefault()
inside the event handler to stop that built-in action while still keeping the event itself active.
JavaScript
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault(); // stops the page from reloading
console.log("Form submission stopped!");
});
11. How do events interact with Shadow DOM?
JavaScript handles events in relation to the Shadow DOM, but the way they propagate and are scoped differs from the regular DOM.
- Event Propagation: Events inside a Shadow DOM bubble up to the shadow root boundary but do not automatically cross into the light DOM unless explicitly configured.
- Event Retargeting: When an event originates inside a Shadow DOM, its target is retargeted to an element in the light DOM (like the shadow host) to prevent exposing internal DOM structure.
- Custom Events: To let events escape the Shadow DOM, developers can dispatch custom events with the option
{ composed: true }
.
JavaScript Asynchronous Interview Questions
12. What’s the difference between synchronous and asynchronous JavaScript?
JavaScript can work in two ways: synchronous and asynchronous, and they differ in how tasks are executed.
- Synchronous JavaScript: Code runs one line at a time, in order. Each task must finish before the next one starts. If a task takes too long (like waiting for data), it blocks everything else.
- Asynchronous JavaScript: Allows tasks to start and then continue running in the background (like fetching data). Meanwhile, other code keeps running. When the task finishes, the result is handled through callbacks, promises, or
async/await
.
14. What is Microtasks Vs Macrotasks?
JavaScript schedules asynchronous work into two main queues: microtasks and macrotasks, and they differ in priority and when they are executed.
Microtasks | Macrotasks |
---|
Small tasks queued in the microtask queue (executed immediately after the current call stack is empty, before next macrotask). | Tasks queued in the macrotask (callback) queue, executed after microtasks are cleared. |
Examples: Promise.then , catch , finally , queueMicrotask() , MutationObserver . | Examples: setTimeout , setInterval , setImmediate (Node.js), requestAnimationFrame , I/O events. |
Executed with higher priority (always before macrotasks). | Executed after all microtasks are done. |
Good for short, immediate follow-ups to the current code. | Good for scheduling larger, delayed tasks. |
15. What are the diffrence between setTimeout Vs setInterval Vs requestAnimationFrame.
JavaScript provides different timing functions: setTimeout, setInterval, and requestAnimationFrame, but they differ in purpose and execution style.
setTimeout | setInterval | requestAnimationFrame |
---|
Runs a function once after a delay. | Runs a function repeatedly at fixed intervals. | Runs a function before the next repaint (synced with screen refresh). |
Use: delayed execution. | Use: periodic execution (polling, auto-save). | Use: smooth animations, game loops. |
Canceled with clearTimeout(id) . | Canceled with clearInterval(id) . | Canceled with cancelAnimationFrame(id) . |
16. What is AJAX, and how does it relate to async JavaScript?
AJAX (Asynchronous JavaScript and XML) is a technique that allows web pages to communicate with a server in the background without reloading the whole page.
- It uses
XMLHttpRequest
(older) or fetch
(modern) to send and receive data from a server. - AJAX requests are asynchronous by default, meaning the browser can keep running other JavaScript code while waiting for the server’s response.
- Once the data arrives, a callback, promise, or
async/await
handles it.
17. What are the key differences between Fetch API and XMLHttpRequest in JavaScript?
JavaScript provides two main ways to make network requests
Fetch API | XMLHttpRequest (XHR) |
---|
Promise-based (then , async/await ) : cleaner and modern | Callback-based : more verbose and harder to manage |
Simple, chainable, works well with async/await | Requires manual state checks (readyState , status ) |
Built-in methods like .json() , .text() , .blob() | Manual parsing needed (responseText , responseXML ) |
Supports streaming responses natively | Must wait for full response before processing |
Rejects only on network errors (HTTP errors need manual check) | Provides detailed status codes (e.g., 404, 500) |
Better integration with CORS, Service Workers, and modern APIs | Older, limited flexibility with modern web APIs |
|
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics