🌳
DOM Manipulation

DOM — Basics

Document Object Model
💡 DOM ek family tree jaisa hai — <html> sabse upar (grandparent), uske andar <head>/<body> (children), unke andar aur elements (grandchildren) — poori HTML ek tree structure ban jaati hai jise JavaScript navigate/modify kar sakta hai.

DOM (Document Object Model) browser ka internal representation hai tumhari HTML ka — ek TREE of objects, jaha har HTML element ek "node" hai. JavaScript is tree ko access/modify kar sakta hai — yehi wajah hai ki JavaScript webpage ko DYNAMICALLY change kar sakta hai (content add karna, styles badalna, elements hataना) bina page reload kiye.

document object DOM ka entry point hai — document.title, document.body jaise properties se poore document tak pahunch sakte ho.

console.log(document.title);   // page ka <title>
console.log(document.body);      // <body> element

// DOM tree conceptually:
// document
//   └── html
//       ├── head
//       │   └── title
//       └── body
//           ├── h1
//           └── p
🌳
DOM ek family tree jaisa hai — <html> sabse upar (grandparent), uske andar <head>/<body> (children), unke andar aur elements (grandchildren) — poori HTML ek tree structure ban jaati hai jise JavaScript navigate/modify kar sakta hai.
1 / 6
⚡ झट से Recap
  • DOM = HTML ka tree-structured, JavaScript-accessible representation
  • document = entry point, poore DOM tak pahunchne ke liye
  • DOM change karna = page dynamically update, bina reload ke
इस page में (2 subtopics)

Agar JavaScript DOM elements access karne se PEHLE chal jaaye (jaise <head> mein <script> daal do bina defer ke), elements abhi exist hi nahi karte — DOMContentLoaded event ye guarantee deta hai ki poora HTML parse ho chuka hai, ab safely DOM access kar sakte ho.

document.addEventListener("DOMContentLoaded", () => {
  console.log("DOM poori tarah load ho chuka hai, ab safe hai!");
  const button = document.querySelector("#myButton");   // ab element guaranteed exist karta hai
});
💡Tip: Modern practice: <script> tag ko </body> ke bilkul pehle rakhna (page ke end mein), ya defer attribute use karna — dono approaches DOMContentLoaded wait karne ki zaroorat almost khatam kar dete hain.

getElementsByClassName()/getElementsByTagName() "live" collections return karte hain — DOM change hone par automatically update hote hain. querySelectorAll() "static" hai — snapshot leta hai, baad ke DOM changes reflect nahi karta.

const liveList = document.getElementsByClassName("item");   // LIVE
const staticList = document.querySelectorAll(".item");          // STATIC

// Naya .item element add karne ke baad:
// liveList.length automatically badh jaayega
// staticList.length WAHI rahega jo query karte waqt tha
💡Tip: Ye subtle farq confusing bugs de sakta hai — agar loop ke andar DOM modify kar rahe ho (jaise elements remove karna), live collections unpredictable behave kar sakti hain. Static (querySelectorAll) usually safer hai.