What is the DOM?#
When the browser loads HTML, it builds a tree of objects called the DOM (Document Object Model). JavaScript can read and change this tree - and the page updates instantly.
document
└── html
├── head ── title
└── body
├── h1
└── button
DOM browser के अंदर बना HTML page का पेड़ (tree) है। हर tag एक object बन जाता है। JavaScript इस पेड़ की किसी भी डाली (element) को ढूंढ सकती है, उसका text या रंग बदल सकती है, नई डाली जोड़ सकती है - और page तुरंत बदल जाता है।
Selecting and changing elements#
| Task | Code |
|---|---|
| select one / all | document.querySelector("css"), document.querySelectorAll("css") |
| text | el.textContent = "Hi" |
| HTML (trusted content only) | el.innerHTML = "<b>Hi</b>" |
| attribute | img.src = "a.png", el.setAttribute("aria-label", "Close") |
| input value | input.value |
| style | el.style.display = "none" |
| classes | el.classList.add("on"), .remove("on"), .toggle("on") |
Put your <script> at the end of <body> (or use <script defer src="app.js"> in the head) so the elements already exist when the code runs.
Events#
An event is something that happens - a click, a key press, a form submit, the page finishing loading. addEventListener runs your function when it happens.
Common events: click, input (every keystroke), change, submit, keydown, mouseover, scroll, DOMContentLoaded.
The callback receives an event object (e): e.target is the element, e.key is the key pressed, e.preventDefault() cancels the browser's default action.
Creating elements - a to-do list#
Never put text typed by a user into innerHTML. Someone could type <img src=x onerror="stealCookies()">. Use textContent or createElement.
Event delegation#
Instead of one listener per button, put one listener on the parent and check e.target:
list.addEventListener("click", (e) => {
if (e.target.matches("button.delete")) e.target.closest("li").remove();
});
This also works for items added later.
Saving data with localStorage#
localStorage keeps small data in the browser even after closing the tab - Vindhyaedu saves your XP and progress this way.
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme"); // "dark" (always a string)
localStorage.setItem("tasks", JSON.stringify(["Study", "Practice"]));
const tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
localStorage.removeItem("theme");
Summary#
- The DOM is the page as objects; select with
querySelector/querySelectorAll. - Change
textContent,value,styleandclassList; create withcreateElement+append. addEventListener("click" | "input" | "submit", fn); usee.preventDefault()for forms.- Use
textContentfor user input; save small data withlocalStorage+ JSON.