Selecting HTML Elements
Selecting HTML Elements — why it matters
querySelector returns the first element matching a CSS selector, or null if none exists. A generic type argument tells TypeScript the expected element kind, but it does not verify the HTML at runtime. Prefer guard checks when reading or mutating elements that a page might omit.
What you’ll learn
- Explain selecting html elements and the problem it solves.
- Identify the relevant compile-time checks and runtime responsibilities.
- Run the example, predict its output, and try a realistic modification.
Understand the mechanism
Optional chaining prevents a null selection from throwing. The first call extracts the text; the second supplies an explicit fallback. The browser example shows document.querySelector<HTMLHeadingElement>.
querySelector<HTMLButtonElement>("#save") is a compile-time assertion about the expected tag, not a runtime HTML tag test.
Follow the concept flow
Run the primary TypeScript example
Save as selecting-html-elements.ts. The following program passed strict TypeScript compilation, and the displayed output was captured by executing its emitted JavaScript with Node.js 22.16.0.
TypeScript source
function headingText(element: Pick<HTMLElement, "textContent"> | null): string {
return element?.textContent?.trim() || "Heading missing";
}
console.log(headingText({ textContent: " Lesson 1 " }));
console.log(headingText(null));Verified output
Lesson 1
Heading missingCompile: npx tsc --strict --target es2022 --module commonjs selecting-html-elements.ts; run: node selecting-html-elements.js. For Node.js API examples, install @types/node first. For browser projects, use the browser-specific instructions below.
The example runs in Node.js 22.16.0; if it reads runtime environment details, your displayed values may differ.
Trace the result
Optional chaining prevents a null selection from throwing. The first call extracts the text; the second supplies an explicit fallback. The browser example shows document.querySelector<HTMLHeadingElement>.
Predict what changes if you alter one input. Then run the code to compare your reasoning with the real output.
Build the real browser interaction
Real browser lab: This TypeScript targets actual DOM APIs and was successfully type-checked against the DOM library. It requires a browser; its runtime interaction was not simulated in Node.js. Save the two files together, compile the TypeScript, and serve this folder through a local HTTP server such as python3 -m http.server 8000 (especially important for modules and workers).
index.html
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>TypeScript browser lab</title></head><body>
<h1 id="title">TypeScript lesson</h1><button id="action">Run</button><p id="output"></p>
<script type="module" src="./app.js"></script>
</body></html>app.ts
const title = document.querySelector<HTMLHeadingElement>("#title");
const missing = document.querySelector<HTMLButtonElement>("#not-there");
if (title) title.textContent = "Selected safely";
console.log(missing === null);Compile: npx tsc --strict --target es2022 --module es2022 --lib es2022,dom app.ts. For the worker example also compile worker.ts with --lib es2022,webworker. Then open the served HTML page in a browser to interact with it.
Common mistake and correction
querySelector<HTMLButtonElement>("#save") is a compile-time assertion about the expected tag, not a runtime HTML tag test.
Identify whether the failure is a type-checking issue, a configuration issue, or a runtime behavior issue before choosing a fix.
Practice the concept
Select a paragraph by class and change its text only after checking that the element exists.
Write down your expected result first. For configuration examples, compare compiler output and diagnostics; for test examples, make the assertion fail deliberately to verify that the tool reports it.
Check your understanding
What to remember
querySelector returns the first element matching a CSS selector, or null if none exists.
Run the primary example, then complete the practice task or environment-specific lab.
Reaching the recap and completing the quizzes are separate milestones.