Selecting Elements
In this page:
Selecting by ID
document.getElementById returns HTMLElement | null typed generically, so accessing a property specific to, say, an input requires an explicit type assertion or narrowing after confirming the element actually exists.
Example: 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);
Using querySelector
querySelector is generic and can be called with a specific element type parameter, like querySelector<HTMLButtonElement>('.submit'), so the returned value already has the right type instead of a generic Element.
Example: Using querySelector
const button = document.createElement("button");
button.className = "submit";
document.body.appendChild(button);
const btn = document.querySelector<HTMLButtonElement>(".submit");
console.log(btn?.tagName);
Selecting Multiple Elements
querySelectorAll returns a typed NodeListOf<T> covering every match for a CSS selector, letting you iterate with a forEach where each item already carries the specific element type you asked for.
Example: 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));
Selecting by Class
Selecting elements by class name with getElementsByClassName returns an HTMLCollectionOf<Element>, a live collection that automatically updates if matching elements are added or removed from the page later.
Example: 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);
Handling Missing Elements
Because any of these selector methods can legitimately return null or an empty collection if the markup doesn't match, always narrow with a null check or a length check before touching properties on the result — TypeScript will insist on it in strict mode.
Example: Handling Missing Elements
const el = document.getElementById("does-not-exist");
if (el === null) {
console.log("Element not found");
} else {
console.log(el.id);
}
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: