DOM Fundamentals & Querying Elements
1. Simple Definition
DOM (Document Object Model) HTML webpage ka browser ke andar bana ek live Tree-like Structure hota hai. Jab browser HTML load karta hai, toh har ek HTML tag ko ek JavaScript Object (Node) bana deta hai. JavaScript is DOM Tree ke zariye kisi bhi element ko select kar sakti hai, uska text change kar sakti hai aur styling dynamically badal sakti hai.
2. Real-Life Analogy
Ek khandan ka Family Tree: Dada ji (<html>) → Papa (<body>) → Bachhe (<h1>, <p>, <button>).
JavaScript family head hai jo kisi bhi member ko uske nickname (Class) ya Aadhar card number (ID) se bula kar bol sakta hai: "Tum red shirt pehno!" (Styling update).
3. Why Do We Need It?
Bina DOM ke JavaScript screen par kuch bhi change nahi kar sakti. Counter ka number 1 se 2 hona, live search filter hona, aur dark mode par background black hona DOM ke zariye hi hota hai.
4. Syntax: Element Selectors
// 1. Single Element Selectors
const title = document.getElementById("main-title");
const firstBtn = document.querySelector(".btn-primary"); // Uses CSS selector!
// 2. Multiple Elements Selector (Returns a NodeList)
const allCards = document.querySelectorAll(".card");
allCards.forEach(card => {
console.log(card);
});
// 3. Updating Text & HTML
title.textContent = "New Heading Text"; // Safe plain text
title.innerHTML = "<span style='color: red;'>Rich HTML Text</span>";
5. Basic Example (Interactive DOM Inspector)
<div class="counter-box">
<h2 id="counter-value">0</h2>
<button id="increment-btn" class="btn btn-primary">Count Badhao +1</button>
</div>
<script>
let count = 0;
const display = document.querySelector("#counter-value");
const btn = document.querySelector("#increment-btn");
btn.addEventListener("click", () => {
count++;
display.textContent = count; // Live DOM update!
});
</script>
6. Output / Expected Result
7. Code Explanation: textContent vs innerHTML
| Property | What It Does | Security & Speed |
|---|---|---|
textContent |
Sirf plain unformatted text update karta hai (Tags render nahi hote) | ⭐ 100% Safe from XSS & Ultra Fast |
innerHTML |
String ke andar ke HTML tags ko parse karke live DOM nodes banata hai | ⚠️ Risky! User input ke sath XSS attacks ho sakte hain |
8. Real-World Example
Notifications counter badge: jab naya message aata hai, JavaScript badge.textContent = newCount; karke number update kar deti hai bina page reload ke.
9. Common Mistakes
document.querySelector("btn") — agar class hai toh dot .btn aur agar ID hai toh hash #btn lagana compulsory hai (bilkul CSS syntax ki tarah!).
10. Best Practices
- Single element ke liye
document.querySelector()aur multiple ke liyedocument.querySelectorAll()ko standard banayein. - Plain text update karne ke liye hamesha
textContentuse karein,innerHTMLnahi.
11. Try It Yourself
Playground me ek <p id="demo"> banayein aur JS se uska textContent change karein.
12. Challenge
Ek Live Character Counter banayein jo textarea me type hone wale characters ki length realtime me count karke screen par dikhaye (textarea.value.length).
13. Interview Questions
Answer:
• HTMLCollection (returned by getElementsByClassName) ek Live Collection hai jo DOM change hone par khud update hoti hai, par isme .forEach() method nahi hota.
• NodeList (returned by querySelectorAll) ek Static Snapshot hai jisme modern .forEach() method directly chalta hai.
14. Quick Revision
- DOM = Live tree of HTML elements in memory.
querySelector / querySelectorAlluse CSS syntax.textContentis safe;innerHTMLis vulnerable.
15. FAQ
Q1. innerText aur textContent me kya difference hai?
innerText CSS styling ko respect karta hai (agar element display: none hai toh uska text return nahi karega). textContent bina kisi CSS calculation ke seedha raw text return karta hai aur 10 guna fast hota hai.
Q2. document object kahan se aata hai?
Ye browser ke global window object ka child property hai (window.document).
Q3. Agar element page par na mile toh querySelector kya return karta hai?
null return karta hai.
Q4. DOM elements ko cache karke rakhna kyun zaroori hai?
Loop ke andar baar-baar document.querySelector() call karne se performance slow hoti hai. Element ko ek baar variable me store karein.
Q5. Shadow DOM kya hota hai?
Web Components ka encapsulated private DOM jiska CSS bahar ke webpage par leak nahi hota.
DOM Fundamentals & Querying Elements
1. Simple Definition
The DOM (Document Object Model) is the tree-like programmatic representation of an HTML document created by the web browser in memory. Through the DOM, JavaScript can inspect, read, modify, add, or delete any HTML tag, attribute, or CSS style in real time.
2. Real-Life Analogy
The root trunk of the tree is window.document. The thick main branches are <html>, <head>, and <body>. Smaller branches are <main>, <section>, and <ul>. The individual green leaves at the very tips are text nodes and buttons. JavaScript is the gardener who can prune, paint, or graft new leaves anywhere on the tree!
3. Modern Element Querying Methods
| Method | Returns | Recommendation |
|---|---|---|
document.querySelector(selector) |
First matching element or null |
✅ Primary Choice: Uses standard CSS selector syntax. |
document.querySelectorAll(selector) |
Static NodeList of all matches |
✅ Best Choice: Supports .forEach() iteration. |
document.getElementById(id) |
Single element with exact ID | ⚡ Fastest performance for known IDs. |
getElementsByClassName() |
Live HTMLCollection | ⚠️ Legacy API; live updating can cause unexpected loop glitches. |
4. Syntax & Basic Usage
// Query by class, ID, or complex CSS selector
const heroTitle = document.querySelector(".hero-banner h1");
const submitBtn = document.querySelector("#submit-btn");
// Query all matching cards and iterate
const cards = document.querySelectorAll(".product-card");
cards.forEach(card => {
card.style.borderColor = "#3b82f6";
});
5. Common Mistakes
Writing document.querySelector("my-class") searches for an HTML tag <my-class>, not a class! Always include the dot . for classes and hash # for IDs: document.querySelector(".my-class")!
6. Best Practices
- Use
querySelectorandquerySelectorAllfor consistent CSS selector semantics. - Cache DOM queries in variables rather than repeatedly querying the DOM inside loops.
- Always verify whether an element exists (
if (el)) before accessing its properties.
7. Practice Exercise
Query all paragraphs with class .note on the page and change their text color to dark blue and font weight to 600 using querySelectorAll() and forEach().
8. Interview Questions
Answer: An HTMLCollection is a live collection containing only element nodes (automatically updates if elements are added/removed in the DOM). A NodeList (returned by querySelectorAll) is a static snapshot that can contain elements, text nodes, and comments, and supports .forEach() directly.
9. Summary / Cheat Card
- The DOM represents HTML elements as programmable JavaScript objects.
querySelectorfinds the first match;querySelectorAllreturns all matches.- Cache DOM references to optimize browser performance.
10. FAQ
Q1. Can querySelector accept multiple selectors separated by commas?
Yes! document.querySelector(".header, .sidebar") returns whichever element appears first in document order.