Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🖱️ Days 8–14 – Data, DOM और Events  ·  दिन 10

दिन 10: DOM: Page चुनना और बदलना

⏱ 90 min📶 Intermediate🎯 100% self-study
दिन 10 / 30

✅ आज आप सीखेंगे

  • 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 एक पेड़ है

documenthtmlbodyarticle.cardh3 · p.price · button
Browser आपके HTML को ऐसे objects बनाता है जिन्हें आप पढ़ और बदल सकते हैं
🧠 HTML बनाम DOM

HTML आपकी लिखी text file है। DOM memory में live पेड़ है। JavaScript DOM बदलता है – View Source अब भी original HTML दिखाता है, जबकि DevTools → Elements मौजूदा DOM दिखाता है।

Elements चुनना

HTML + JavaScript
<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>
▶  querySelector, querySelectorAll, getElementById, closest
Methodलौटाता हैTip
querySelector(css) ⭐पहला element या nullकोई भी CSS selector: "#id", ".class", "form input[name=phone]"
querySelectorAll(css)NodeList (forEach चलता है)map जैसे methods के लिए [...list]
getElementById(id)Element या nullArgument में # नहीं
el.closest(css)सबसे पास का ancestor (या ख़ुद)Click हुए button वाला card ढूँढना
el.querySelector(css)सिर्फ़ el के अंदर खोजcard.querySelector(".price")

Text और HTML बदलना

HTML + JavaScript
<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>
▶  textContent for text, innerHTML only for trusted HTML
⚠️ innerHTML + user input = XSS

Users का लिखा text (नाम, reviews, search terms) कभी innerHTML में न डालें। Attacker script डालकर logins चुरा सकता है। textContent लें, या elements बनाएँ (Day 12)। Day 26 security गहराई से सिखाता है।

classList और style

HTML + JavaScript
<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>
▶  Prefer classes (CSS does the design); use style for one-off values
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

HTML + JavaScript
<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>
▶  src, alt, dataset, aria-pressed, .value and .checked
पढ़ना / लिखनाउदाहरण
आम propertiesimg.src, a.href, input.value, input.checked, el.id, btn.disabled
कोई भी attributeel.getAttribute("aria-label"), el.setAttribute("aria-pressed", "true"), el.removeAttribute("hidden")
data-* attributesdata-price="650" → el.dataset.price ("650", string)
hiddenel.hidden = true – बिना CSS छिपाता है

असली task: dark-mode switch

HTML + JavaScript
<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>
▶  JS toggles one class on &lt;html&gt;; CSS variables (CSS Day 12) do the rest

🏅 आज के Job Skills

✔ querySelector/All और closest से elements चुनना✔ textContent से text सुरक्षित बदलना✔ Classes toggle और styles set करना✔ Attributes, data-* और form values पढ़ना-लिखना

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: “Read more” button बनाएँ जो छिपा paragraph दिखाए और अपना text “Read less” कर दे।
Solution देखें
▶  Result
Task 2: जिस menu item का data-price 600 से ऊपर हो उसे “premium” class से highlight करें।
Task 3: 160-character SMS textarea का character counter बनाएँ जो सीमा के पास लाल हो जाए।

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. querySelectorAll लौटाता है…
forEach या spread लें।
2. User का नाम दिखाने का सबसे सुरक्षित तरीक़ा?
कोई HTML parse नहीं होता।
3. data-price="650" पढ़ा जाता है…
यह string है।
4. classList.toggle("x") लौटाता है…
State के लिए उपयोगी।
5. Click हुए button वाला card ढूँढें:
पेड़ में ऊपर जाता है।

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।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या jQuery लूँ?
नए projects में नहीं – jQuery जो करता था (selecting, classes, events, AJAX) अब JavaScript में built-in है। पुराने PHP/WordPress sites में अब भी दिख सकता है।
मेरा querySelector null क्यों लौटाता है?
Selector में typo, element अभी बना नहीं (defer लें), या selector में # / . भूल गए।
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 11: Events, Event Object और Delegation आपकी प्रगति: 10 / 30 (33%) · Lesson 11 / 30 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें