instanceof Narrows DOM Element Types
instanceof checks double as type guards: each branch sees the concrete element class with its own properties instead of the bare Element shape.
Code
// instanceof 在 TS 里同时完成两件事:运行时判断 + 类型收窄
const target: Element | null = document.querySelector('.profile');
if (target instanceof HTMLInputElement) {
// 收窄为 HTMLInputElement:value / disabled / type 都可用
console.log('input value:', target.value);
target.disabled = true;
} else if (target instanceof HTMLAnchorElement) {
// 收窄为 HTMLAnchorElement:href 可用
console.log('anchor href:', target.getAttribute('href'));
} else if (target instanceof HTMLImageElement) {
console.log('image alt:', target.alt);
} else {
console.log('generic element:', target?.tagName ?? 'nothing matched');
}Points of care
documentexist only in browsers — a Node runtime has no shims for them out of the box.
Applying it
The demo output is labeled (input value:, anchor href:, image alt:), so each printed line points back to the operation it originated from.
Statements that matter
const target: Element | null = document.querySelector('.profile');
target.disabled = true;
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does instanceof Narrows DOM Element Types run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.