JavaScript DOM Interview Questions and Answers

Review how JavaScript reads and updates the DOM, selects elements, and creates accessible page content.

Frequently Asked Questions

Important questions are highlighted in the sections below; select one to jump to its answer.

Theoretical JavaScript Interview Questions

Honestly, almost never in modern development. The only semi-legitimate use case is during initial page load for things like third-party ad scripts that need to inject content synchronously. Some legacy testing setups also use it for quick output. But for anything real, methods like innerHTML or appendChild() give you precise control over what changes and when, without the risk of accidentally nuking your entire page. If you see document.write() in a codebase, it's usually a sign the code needs updating.

The innerHTML property lets you read or replace the HTML content inside any element. It's like swapping out the guts of a DOM node in one shot. Quick and convenient for simple updates, but there are real traps to watch out for when using it Read more :

innerHTML is the quick-and-dirty approach: hand it an HTML string and the browser parses and renders it in one go. createElement() and appendChild() are the surgical approach: you build each node by hand, attach event listeners, and insert them precisely where you want. Use innerHTML when you're replacing a chunk of static content. Use createElement() when you need fine control, like building a dynamic list where each item has click handlers. The big difference? innerHTML wipes out existing event listeners on child elements, while appendChild() preserves them.

The DOM (Document Object Model) is the browser's live, in-memory tree representation of your HTML. When the browser parses your HTML, it builds this tree, and JavaScript can then walk, query, and modify it - every element, text node, and attribute becomes an object you can interact with. This is ultimately how all those React and Vue frameworks work under the hood too.

Without the DOM, JavaScript would have no way to interact with the page - it would just be a scripting language with no connection to what users see. The DOM is the bridge between your JavaScript logic and the HTML structure, letting you react to user input, update content dynamically, and build SPAs. Every front-end framework you'll ever use is built on top of DOM APIs.

In practice you'll mostly use querySelector and querySelectorAll since they accept any CSS selector and are more flexible. getElementById is still the fastest for single lookups by id. The older getElementsBy* methods return live HTMLCollections that auto-update as the DOM changes, while querySelectorAll returns a static NodeList - a gotcha that trips people up when looping over elements while mutating the DOM.

A Node is the base type for everything in the DOM tree - elements, text nodes, comments, and even the document itself are all Nodes. An Element is a more specific Node that represents an actual HTML tag with attributes and child elements. HTMLCollection is a live, array-like object from older DOM methods that auto-updates as the DOM changes, which can cause unexpected behavior when iterating - most devs convert it to a real array with Array.from() before looping.

innerHTML parses and renders whatever HTML string you give it, which is powerful but dangerous - never use it with user-supplied content or you're opening yourself up to XSS attacks. textContent just treats everything as a plain string, so it's safe for user data. Rule of thumb: use textContent when you're setting text, innerHTML only when you genuinely need to inject HTML markup you control.

innerHTML is the content between an element's opening and closing tags - it's what's inside. Attributes are metadata on the opening tag itself, like id, class, href, or data-*. To read or write attributes use getAttribute/setAttribute, or the direct property shortcut (element.id, element.className). A common gotcha: some attributes map to differently-named properties (class becomes className in JS), so the direct property approach is usually cleaner when it's available.

Use element.style.propertyName to set inline styles directly - just remember CSS properties become camelCase in JS (background-color becomes backgroundColor). For toggling styles, element.classList.add/remove/toggle is usually a better approach since it keeps your styles in CSS where they belong. Avoid modifying element.style directly for complex styling - it couples your JS to visual concerns and is hard to override with stylesheets.

For mouse events you've got click, dblclick, mousedown, mouseup, mousemove, mouseover, and mouseout - plus the newer mouseenter/mouseleave which don't bubble, unlike mouseover/mouseout. For keyboards: keydown fires first, then keypress (deprecated - avoid it), then keyup. In practice, use keydown for most keyboard handling. Also worth knowing: the input and change events for form fields, and focus/blur for focus management.

addEventListener is the right way to attach event handlers - unlike the old onclick property approach, you can attach multiple handlers for the same event without overwriting each other. The handler receives an event object with all the context you need. Always use named functions when you need to remove the listener later - anonymous arrow functions can't be removed because removeEventListener needs the exact same function reference.

The DOM (Document Object Model) is a programming interface that represents an HTML page as a tree of objects. When a browser loads a page, it builds this tree from the HTML. JavaScript can then select, read, and modify any node in the tree to update what the user sees without reloading the page.

innerHTML reads or writes the HTML content inside an element, including any tags, so tags are parsed and rendered. textContent reads or writes plain text only; any HTML tags are treated as literal text and not rendered. Use textContent when inserting user-provided data to avoid XSS security risks.

querySelector returns the first element that matches a CSS selector, or null if nothing matches. querySelectorAll returns a NodeList of all matching elements (which may be empty). Both accept any valid CSS selector, making them more flexible than getElementById or getElementsByClassName.

target is the element where the event originated, which may be a nested child. currentTarget is the element whose listener is currently handling the event. Delegated handlers commonly inspect target, often with closest, while using currentTarget to refer to the delegation container.

textContent inserts a string as text, so the browser does not parse it as markup. Assigning untrusted input to innerHTML can create attacker-controlled elements or scriptable markup. Use a safe text API unless HTML parsing is intentionally needed and the input is properly sanitized.

A DocumentFragment lets code build a group of nodes off-document and append them together, which can simplify bulk DOM updates. It does not guarantee a measurable performance improvement in every browser or workload, so profile before relying on it as an optimization.

MutationObserver is useful when code must react to DOM changes made by code it does not control. Disconnect the observer when its work is finished or its owning component is removed, and avoid callbacks that continuously trigger more observed mutations.

Events crossing a shadow boundary may be retargeted, so event.target outside the component may refer to the host rather than the internal element. For composed events, composedPath can reveal the propagation path; component code should respect encapsulation and expose intentional interactions.

JavaScript Practical and Coding Interview Questions

Problem: Create a button, register a named click handler, remove it, and verify clicking does not run it.

javascript

const button = document.createElement('button');
let clicks = 0;
function handleClick() {
  clicks += 1;
}

button.addEventListener('click', handleClick);
button.removeEventListener('click', handleClick);
button.click();
console.log(clicks);

Problem: Create a list and a list item with the text 'New topic', append them to the document, and log the item text.

javascript

const list = document.createElement('ul');
const item = document.createElement('li');
item.textContent = 'New topic';
list.append(item);
document.body.append(list);
console.log(list.firstElementChild.textContent);

Problem: Create a paragraph with the class 'status' and text 'Saved', append it to the document, and log its HTML.

javascript

const status = document.createElement('p');
status.className = 'status';
status.textContent = 'Saved';
document.body.append(status);
console.log(status.outerHTML);

Problem: Create two list items, remove the second one, and log the remaining item text.

javascript

const list = document.createElement('ul');
const keep = document.createElement('li');
const remove = document.createElement('li');
keep.textContent = 'Keep';
remove.textContent = 'Remove';
list.append(keep, remove);
remove.remove();
console.log(list.children.length, list.firstElementChild.textContent);