दिन 10: DOM: Page चुनना और बदलना
✅ आज आप सीखेंगे
- DOM क्या है – page objects के पेड़ के रूप में
- चुनना: querySelector, querySelectorAll, getElementById, closest
- Text बदलना: textContent बनाम innerHTML
- Styling के लिए classList, एक-बार values के लिए style
- Attributes, dataset और form values
🏢 असली दुनिया में
Website पर user जो भी बदलता देखता है – price का बदलना, heart icon का लाल होना, “Out of stock” का आना, dark-mode switch – वह JavaScript का DOM बदलना है। आज आप वे 10 DOM operations सीखेंगे जो असली front-end काम का 90% हैं।
DOM एक पेड़ है
HTML आपकी लिखी text file है। DOM memory में live पेड़ है। JavaScript DOM बदलता है – View Source अब भी original HTML दिखाता है, जबकि DevTools → Elements मौजूदा DOM दिखाता है।
Elements चुनना
<h2 id="title">Today’s sweets</h2>
<ul class="menu">
<li class="item">Kaju Katli</li>
<li class="item special">Ghewar</li>
<li class="item">Rasmalai</li>
</ul>
<pre id="log"></pre>
<script>
const title = document.querySelector('#title'); // first match (CSS selector)
const items = document.querySelectorAll('.menu .item'); // ALL matches (NodeList)
const special = document.querySelector('.item.special');
const byId = document.getElementById('title'); // older, very fast
const lines = [];
lines.push('title text: ' + title.textContent);
lines.push('items found: ' + items.length);
items.forEach((li, i) => lines.push(` ${i}: ${li.textContent}`));
lines.push('special: ' + special.textContent);
lines.push('same element? ' + (title === byId));
lines.push('parent of special: ' + special.closest('ul').className);
document.querySelector('#log').textContent = lines.join('\n');
</script>| Method | लौटाता है | Tip |
|---|---|---|
| querySelector(css) ⭐ | पहला element या null | कोई भी CSS selector: "#id", ".class", "form input[name=phone]" |
| querySelectorAll(css) | NodeList (forEach चलता है) | map जैसे methods के लिए [...list] |
| getElementById(id) | Element या null | Argument में # नहीं |
| el.closest(css) | सबसे पास का ancestor (या ख़ुद) | Click हुए button वाला card ढूँढना |
| el.querySelector(css) | सिर्फ़ el के अंदर खोज | card.querySelector(".price") |
Text और HTML बदलना
<p id="a"></p>
<p id="b"></p>
<p id="c"></p>
<script>
const userInput = '<img src=x onerror="alert(1)"> Aarti';
document.querySelector('#a').textContent = 'Price: ₹900/kg'; // ✅ plain text
document.querySelector('#b').innerHTML = 'Price: <b>₹900</b>/kg'; // ✅ your own trusted HTML
document.querySelector('#c').textContent = 'Hello ' + userInput; // ✅ user text shown safely as text
// document.querySelector('#c').innerHTML = 'Hello ' + userInput; // ❌ would run the attacker’s code
</script>Users का लिखा text (नाम, reviews, search terms) कभी innerHTML में न डालें। Attacker script डालकर logins चुरा सकता है। textContent लें, या elements बनाएँ (Day 12)। Day 26 security गहराई से सिखाता है।
classList और style
<style>
.card { width: 240px; border: 2px solid #e5e7eb; border-radius: 14px; padding: 14px; transition: .2s; }
.card.selected { border-color: #ca8a04; background: #fefce8; }
.card.sold-out { opacity: .5; }
.badge { display: inline-block; background: #16a34a; color: #fff; font-size: 12px; padding: 2px 8px; border-radius: 99px; }
button { margin: 4px 4px 0 0; }
</style>
<article class="card" id="card">
<h3>Kaju Katli <span class="badge">Veg</span></h3>
<p>₹<span id="price">900</span>/kg</p>
<button id="select">Select</button><button id="sold">Toggle sold out</button><button id="sale">Festival price</button>
</article>
<script>
const card = document.querySelector('#card');
document.querySelector('#select').addEventListener('click', () => {
card.classList.toggle('selected'); // add if missing, remove if present
});
document.querySelector('#sold').addEventListener('click', () => {
const soldOut = card.classList.toggle('sold-out');
card.querySelector('.badge').textContent = soldOut ? 'Sold out' : 'Veg';
card.querySelector('.badge').style.background = soldOut ? '#dc2626' : ''; // '' resets to CSS
});
document.querySelector('#sale').addEventListener('click', () => {
document.querySelector('#price').textContent = 810;
card.style.setProperty('border-style', 'dashed');
});
</script>| classList method | क्या करता है |
|---|---|
| add("x") | Class जोड़ो |
| remove("x") | Class हटाओ |
| toggle("x") | जोड़ो/हटाओ; अब है तो true |
| toggle("x", condition) | Boolean से चालू/बंद |
| contains("x") | true/false |
| replace("a", "b") | Classes बदलो |
Attributes, data-* और form values
<img id="photo" src="images/kaju-katli-400.webp" alt="Kaju katli" width="160">
<div>
<button class="pick" data-img="images/ghewar-400.webp" data-name="Ghewar" data-price="650">Ghewar</button>
<button class="pick" data-img="images/rasmalai-400.webp" data-name="Rasmalai" data-price="700">Rasmalai</button>
<button class="pick" data-img="images/ladoo-400.webp" data-name="Besan Ladoo" data-price="500">Ladoo</button>
</div>
<label>Qty (kg) <input id="qty" type="number" value="1" min="0.25" step="0.25"></label>
<label><input id="gift" type="checkbox"> Gift wrap (+₹50)</label>
<p id="total"></p>
<script>
let price = 900;
function update() {
const qty = Number(document.querySelector('#qty').value); // .value is always a string
const gift = document.querySelector('#gift').checked; // .checked for checkboxes
document.querySelector('#total').textContent = `Total ₹${price * qty + (gift ? 50 : 0)}`;
}
document.querySelectorAll('.pick').forEach(btn => btn.addEventListener('click', () => {
const photo = document.querySelector('#photo');
photo.src = btn.dataset.img; // data-img → dataset.img
photo.alt = btn.dataset.name;
price = Number(btn.dataset.price);
document.querySelectorAll('.pick').forEach(b => b.setAttribute('aria-pressed', b === btn));
update();
}));
document.querySelector('#qty').addEventListener('input', update);
document.querySelector('#gift').addEventListener('change', update);
update();
</script>| पढ़ना / लिखना | उदाहरण |
|---|---|
| आम properties | img.src, a.href, input.value, input.checked, el.id, btn.disabled |
| कोई भी attribute | el.getAttribute("aria-label"), el.setAttribute("aria-pressed", "true"), el.removeAttribute("hidden") |
| data-* attributes | data-price="650" → el.dataset.price ("650", string) |
| hidden | el.hidden = true – बिना CSS छिपाता है |
असली task: dark-mode switch
<style>
:root { --bg: #fff; --text: #111827; --card: #f1f5f9; }
:root.dark { --bg: #0b1120; --text: #e5e7eb; --card: #1e293b; }
body { background: var(--bg); color: var(--text); transition: background .3s, color .3s; }
.panel { background: var(--card); padding: 12px 16px; border-radius: 12px; margin-top: 10px; }
</style>
<button id="theme" aria-pressed="false">🌙 Dark mode</button>
<div class="panel"><h3>Order #1042</h3><p>2 kg Kaju Katli · ₹1,800</p></div>
<script>
const btn = document.querySelector('#theme');
btn.addEventListener('click', () => {
const dark = document.documentElement.classList.toggle('dark');
btn.setAttribute('aria-pressed', dark);
btn.textContent = dark ? '☀️ Light mode' : '🌙 Dark mode';
});
</script>🏅 आज के Job Skills
Practice tasks
🏋️ Practice – ख़ुद करें
Solution देखें
Quick quiz
🧠 Quick Quiz – ख़ुद को जाँचें
Interview corner
💼 Interview Corner
textContent बनाम innerText बनाम innerHTML?
textContent सभी nodes का कच्चा text पढ़ता/लिखता है (तेज़, CSS नज़रअंदाज़); innerText दिखने वाला rendered text (layout trigger करता है); innerHTML HTML parse करता है – ताक़तवर पर अविश्वसनीय data के साथ XSS ख़तरा।
NodeList बनाम HTMLCollection?
querySelectorAll static NodeList लौटाता है (forEach चलता है); getElementsByClassName live HTMLCollection लौटाता है जो DOM बदलने पर update होता है और forEach नहीं रखता। Array.from या spread से बदलें।
सारांश
- DOM आपके page का live पेड़ है।
- querySelector / querySelectorAll / closest elements चुनते हैं।
- Text के लिए textContent; innerHTML सिर्फ़ भरोसेमंद HTML के लिए।
- Design states के लिए classList, data के लिए dataset और attributes।
Day 11: events – clicks, typing, keyboard shortcuts, event object और event delegation।
