Elements को Select करना
In this page:
const element = document.querySelector<HTMLElementType>("selector");
const byId = document.getElementById("id") as HTMLElementType;
ID से Select करना
document.getElementById generically HTMLElement | null typed return करता है, इसलिए किसी specific property को access करने के लिए, जैसे एक input की, element असल में मौजूद है confirm करने के बाद एक explicit type assertion या narrowing चाहिए।
उदाहरण: Selecting by ID
const div = document.createElement("div");
div.id = "app";
document.body.appendChild(div);
const el = document.getElementById("app");
if (el) console.log(el.id);
querySelector उपयोग करना
querySelector generic है और एक specific element type parameter के साथ call किया जा सकता है, जैसे querySelector<HTMLButtonElement>('.submit'), इसलिए returned value में एक generic Element के बजाय already सही type होता है।
उदाहरण: Using querySelector
const button = document.createElement("button");
button.className = "submit";
document.body.appendChild(button);
const btn = document.querySelector<HTMLButtonElement>(".submit");
console.log(btn?.tagName);
कई Elements Select करना
querySelectorAll एक CSS selector के हर match को cover करने वाला एक typed NodeListOf<T> return करता है, आपको forEach से iterate करने देते हुए जहां हर item में already आपके मांगे specific element type मौजूद है।
उदाहरण: Selecting Multiple Elements
document.body.innerHTML = '<p class="item">A</p><p class="item">B</p>';
const items = document.querySelectorAll<HTMLParagraphElement>(".item");
items.forEach((el) => console.log(el.textContent));
Class से Select करना
Class name से elements select करना getElementsByClassName के साथ एक HTMLCollectionOf<Element> return करता है, एक live collection जो बाद में page में matching elements add या remove होने पर अपने आप update होती है।
उदाहरण: Selecting by Class
document.body.innerHTML = '<span class="tag">x</span><span class="tag">y</span>';
const tags: HTMLCollectionOf<Element> = document.getElementsByClassName("tag");
console.log(tags.length);
Missing Elements Handle करना
क्योंकि इनमें से कोई भी selector method agar markup match न करे तो legitimately null या एक empty collection return कर सकता है, result पर properties छूने से पहले हमेशा एक null check या length check से narrow करें — strict mode में TypeScript इस पर ज़ोर देगा।
उदाहरण: Handling Missing Elements
const el = document.getElementById("does-not-exist");
if (el === null) {
console.log("Element not found");
} else {
console.log(el.id);
}
getElementByIdके result को बिना null check के उपयोग करना, जब यहHTMLElement | nullreturn करता है।- यह उम्मीद करना कि
querySelector(".submit")एकHTMLButtonElementहोगा, जब generic के बिना यह सिर्फElement | nullहै। NodeListOfयाHTMLCollectionपर directly.mapcall करना, क्योंकि वे arrays नहीं हैं।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: