← Back to TypeScript Course | Chapter 12: TypeScript with DOM | Lesson 2 of 6

Selecting Elements

TypeScript can select HTML elements with methods such as getElementById, querySelector, and querySelectorAll. Because elements may not exist, TypeScript encourages safe handling of null values.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.