Interview Q&A · JavaScript · 14 questions in this topic

DOM, Events & Browser APIs — JavaScript Interview Q&A

All JavaScript topics

Frontend runtime — selecting and mutating the DOM, event flow, forms and storage. Part of DOM & Browser · 204 questions in the JavaScript bank.

How do you select and modify DOM elements?

Answer

querySelector(All) with CSS selectors (modern default), getElementById for ids; modify via textContent (safe text), classList (classes), setAttribute, and style. Batch reads/writes to avoid layout thrash; prefer textContent over innerHTML (XSS safety).

textContent-for-text, classList-for-style is the safe-manipulation duo.

Example

Example.jsjs
const el = document.querySelector('#app');
el.textContent = 'safe text'; // no HTML parsing (XSS-safe)
el.classList.toggle('open');

How do capturing and bubbling work (event phases)?

Answer

Events travel capture (window→target) then bubble (target→window); listeners default to bubble, { capture: true } catches descending. stopPropagation halts travel; preventDefault cancels default action (orthogonal concerns). Target vs currentTarget distinguishes origin from handling node.

Capture-down, bubble-up, target-in-middle is the phase picture.

Key points

  1. 1Capture — descending, opt-in.
  2. 2Target — at the node.
  3. 3Bubble — ascending, default.

Example

Example.jsjs
el.addEventListener('click', handler); // bubble (default)
document.addEventListener('click', h2, { capture: true }); // descending

💡 stopPropagation-vs-preventDefault is the distinction to nail.

What is event delegation and why is it better?

Answer

One listener on a parent handles events from many children via event.target matching — fewer listeners, automatic coverage of dynamic nodes, less memory. Tables/lists/menus delegate; closest() finds the semantic ancestor.

Single-parent-listener-plus-target-match is the pattern.

Example

Example.jsjs
list.addEventListener('click', (e) => {
  const item = e.target.closest('li'); // semantic ancestor
  if (item) handle(item.dataset.id);
});

💡 Dynamic-nodes-covered-free is the delegation payoff.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits