Skip to content

5. DOM and Browser Concepts ​

These topics are extremely important for frontend and React interviews because browsers and UI interactions are based on the DOM.


Topics Covered ​

  • DOM Selection
  • Event Handling
  • Event Bubbling
  • Event Delegation
  • Local Storage
  • Session Storage
  • Debouncing
  • Throttling

1. What is DOM? ​

DOM stands for Document Object Model.

When browser loads HTML, it converts the page into a tree-like structure called DOM.

JavaScript can use DOM to:

  • Change content
  • Change styles
  • Add/remove elements
  • Handle events

Example HTML ​

html
<h1 id="title">Hello</h1>

Access DOM with JavaScript ​

js
const element = document.getElementById("title");

console.log(element);

2. DOM Selection Methods ​

Used to select HTML elements.


getElementById() ​

Selects element by ID.

js
const title = document.getElementById("title");

getElementsByClassName() ​

Selects elements using class name.

js
const items = document.getElementsByClassName("item");

Returns HTMLCollection.


getElementsByTagName() ​

js
const divs = document.getElementsByTagName("div");

querySelector() (VERY IMPORTANT) ​

Returns FIRST matching element.

js
const btn = document.querySelector(".btn");

querySelectorAll() ​

Returns all matching elements.

js
const buttons = document.querySelectorAll(".btn");

Returns NodeList.


Difference Between querySelector and querySelectorAll ​

querySelector()querySelectorAll()
First matching elementAll matching elements
Single elementNodeList

3. Changing DOM Content ​


Change Text ​

js
const title = document.getElementById("title");

title.innerText = "Welcome";

Change HTML ​

js
title.innerHTML = "<span>Hello</span>";

Change Style ​

js
title.style.color = "red";

Add Class ​

js
title.classList.add("active");

Remove Class ​

js
title.classList.remove("active");

Toggle Class ​

js
title.classList.toggle("dark");

4. Event Handling (VERY IMPORTANT) ​

Events are user interactions.

Examples:

  • Click
  • Input
  • Submit
  • Mouseover
  • Keypress

Add Event Listener ​

js
const btn = document.querySelector("button");

btn.addEventListener("click", () => {
  console.log("Button clicked");
});

Why addEventListener is Preferred ​

  • Multiple events possible
  • Cleaner code
  • Better control

Common Events ​

EventDescription
clickMouse click
inputInput field change
submitForm submit
keydownKey pressed
mouseoverMouse hover

Example — Input Event ​

js
const input = document.querySelector("input");

input.addEventListener("input", (e) => {
  console.log(e.target.value);
});

5. Event Bubbling (VERY IMPORTANT) ​

Event bubbling means event travels from child → parent.


Example ​

html
<div id="parent">
  <button id="child">Click</button>
</div>
js
document.getElementById("child").addEventListener("click", () => {
  console.log("Child clicked");
});

document.getElementById("parent").addEventListener("click", () => {
  console.log("Parent clicked");
});

Output ​

js
Child clicked
Parent clicked

Why? ​

Event first occurs on child, then bubbles upward to parent.


Stop Event Bubbling ​

js
event.stopPropagation();

Example ​

js
btn.addEventListener("click", (event) => {
  event.stopPropagation();
});

6. Event Delegation (VERY IMPORTANT) ​

Instead of adding event listeners to multiple child elements, add one listener to parent.

Uses event bubbling internally.


Example ​

html
<ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>
js
document.getElementById("list").addEventListener("click", (e) => {
  console.log(e.target.textContent);
});

Benefits of Event Delegation ​

  • Better performance
  • Less memory usage
  • Works for dynamically added elements

Real Interview Example ​

Useful in:

  • Dynamic lists
  • Tables
  • Menus
  • React event systems

7. Local Storage ​

Used to store data in browser permanently.

Data remains even after browser refresh or close.


Store Data ​

js
localStorage.setItem("name", "Dipak");

Get Data ​

js
const data = localStorage.getItem("name");

console.log(data);

Remove Data ​

js
localStorage.removeItem("name");

Clear All ​

js
localStorage.clear();

Important Points ​

  • Stores only strings
  • Persistent storage
  • Around 5–10MB

Store Objects ​

Use JSON.stringify().

js
const user = {
  name: "Dipak",
};

localStorage.setItem("user", JSON.stringify(user));

Retrieve Object ​

js
const data = JSON.parse(localStorage.getItem("user"));

console.log(data);

8. Session Storage ​

Similar to localStorage but cleared when tab closes.


Example ​

js
sessionStorage.setItem("token", "123");

Difference Between localStorage and sessionStorage ​

localStoragesessionStorage
PermanentRemoved after tab close
Shared across tabsSpecific to one tab
5–10MBAround 5MB

9. Debouncing (VERY IMPORTANT) ​

Debouncing delays function execution until user stops triggering event for certain time.


Real-Life Example ​

Search input optimization.

Instead of API call on every key press, wait until typing stops.


Example ​

js
function debounce(fn, delay) {
  let timer;

  return function (...args) {
    clearTimeout(timer);

    timer = setTimeout(() => {
      fn(...args);
    }, delay);
  };
}

Usage Example ​

js
const search = debounce(() => {
  console.log("API Call");
}, 500);

input.addEventListener("input", search);

How Debouncing Works ​

If user types quickly:

  • Previous timer clears
  • New timer starts

Function runs only after delay completes.


Benefits of Debouncing ​

  • Improves performance
  • Reduces API calls
  • Better user experience

Common Uses ​

  • Search bars
  • Resize events
  • Auto-save
  • Input validation

10. Throttling ​

Throttling limits function execution to once within specific time interval.


Example ​

js
function throttle(fn, delay) {
  let lastCall = 0;

  return function (...args) {
    const now = Date.now();

    if (now - lastCall >= delay) {
      lastCall = now;
      fn(...args);
    }
  };
}

Difference Between Debouncing and Throttling ​

DebouncingThrottling
Executes after delay endsExecutes at intervals
Waits for user to stopLimits execution frequency
Best for searchBest for scroll/resize

Real-Life Example ​

Debouncing ​

Search bar API calls.

Throttling ​

Scroll event optimization.


Important Browser APIs ​


setTimeout() ​

Runs once after delay.

js
setTimeout(() => {
  console.log("Hello");
}, 1000);

setInterval() ​

Runs repeatedly.

js
setInterval(() => {
  console.log("Running");
}, 1000);

Clear Timeout ​

js
clearTimeout(id);

Clear Interval ​

js
clearInterval(id);

Most Asked Interview Questions ​


Q1. Difference Between localStorage and sessionStorage ​

localStoragesessionStorage
PermanentRemoved after tab close
Shared across tabsTab specific
5–10MBAround 5MB

Q2. What is Event Bubbling? ​

Event bubbles from child → parent.

js
child.addEventListener("click", () => {});
parent.addEventListener("click", () => {});

Q3. What is Debouncing? ​

Technique used to delay function execution.

Used heavily in:

  • Search inputs
  • API optimization

Q4. What is Event Delegation? ​

Using one event listener on parent instead of multiple child listeners.

Improves performance.


Important Interview Focus Areas ​

Most asked topics:

  • Event bubbling
  • Event delegation
  • Debouncing
  • Local storage
  • DOM selection
  • Event handling

Best Practices ​

  • Prefer addEventListener
  • Use event delegation for dynamic elements
  • Use debouncing for API-heavy operations
  • Avoid excessive DOM manipulation
  • Store objects using JSON.stringify()

© 2025 DDocs · Dipak's Documentation Guide