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
<h1 id="title">Hello</h1>Access DOM with JavaScript
const element = document.getElementById("title");
console.log(element);2. DOM Selection Methods
Used to select HTML elements.
getElementById()
Selects element by ID.
const title = document.getElementById("title");getElementsByClassName()
Selects elements using class name.
const items = document.getElementsByClassName("item");Returns HTMLCollection.
getElementsByTagName()
const divs = document.getElementsByTagName("div");querySelector() (VERY IMPORTANT)
Returns FIRST matching element.
const btn = document.querySelector(".btn");querySelectorAll()
Returns all matching elements.
const buttons = document.querySelectorAll(".btn");Returns NodeList.
Difference Between querySelector and querySelectorAll
querySelector() | querySelectorAll() |
|---|---|
| First matching element | All matching elements |
| Single element | NodeList |
3. Changing DOM Content
Change Text
const title = document.getElementById("title");
title.innerText = "Welcome";Change HTML
title.innerHTML = "<span>Hello</span>";Change Style
title.style.color = "red";Add Class
title.classList.add("active");Remove Class
title.classList.remove("active");Toggle Class
title.classList.toggle("dark");4. Event Handling (VERY IMPORTANT)
Events are user interactions.
Examples:
- Click
- Input
- Submit
- Mouseover
- Keypress
Add Event Listener
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
| Event | Description |
|---|---|
click | Mouse click |
input | Input field change |
submit | Form submit |
keydown | Key pressed |
mouseover | Mouse hover |
Example — Input Event
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
<div id="parent">
<button id="child">Click</button>
</div>document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked");
});
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked");
});Output
Child clicked
Parent clickedWhy?
Event first occurs on child, then bubbles upward to parent.
Stop Event Bubbling
event.stopPropagation();Example
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
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
</ul>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
localStorage.setItem("name", "Dipak");Get Data
const data = localStorage.getItem("name");
console.log(data);Remove Data
localStorage.removeItem("name");Clear All
localStorage.clear();Important Points
- Stores only strings
- Persistent storage
- Around 5–10MB
Store Objects
Use JSON.stringify().
const user = {
name: "Dipak",
};
localStorage.setItem("user", JSON.stringify(user));Retrieve Object
const data = JSON.parse(localStorage.getItem("user"));
console.log(data);8. Session Storage
Similar to localStorage but cleared when tab closes.
Example
sessionStorage.setItem("token", "123");Difference Between localStorage and sessionStorage
| localStorage | sessionStorage |
|---|---|
| Permanent | Removed after tab close |
| Shared across tabs | Specific to one tab |
| 5–10MB | Around 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
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn(...args);
}, delay);
};
}Usage Example
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
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
| Debouncing | Throttling |
|---|---|
| Executes after delay ends | Executes at intervals |
| Waits for user to stop | Limits execution frequency |
| Best for search | Best for scroll/resize |
Real-Life Example
Debouncing
Search bar API calls.
Throttling
Scroll event optimization.
Important Browser APIs
setTimeout()
Runs once after delay.
setTimeout(() => {
console.log("Hello");
}, 1000);setInterval()
Runs repeatedly.
setInterval(() => {
console.log("Running");
}, 1000);Clear Timeout
clearTimeout(id);Clear Interval
clearInterval(id);Most Asked Interview Questions
Q1. Difference Between localStorage and sessionStorage
| localStorage | sessionStorage |
|---|---|
| Permanent | Removed after tab close |
| Shared across tabs | Tab specific |
| 5–10MB | Around 5MB |
Q2. What is Event Bubbling?
Event bubbles from child → parent.
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()