← 中文资源

简体中文版本

instanceof 收窄 DOM 元素类型

instanceof 一举两得:运行时判断实例归属,编译期把 Element 收窄成具体元素类,各分支里 value、href、alt 等专属属性直接可用。

阅读英文原文

使用要点

  • 浏览器才是这里的运行环境:document 在 Node 里拿不到。
  • 跑完文件,输出里会留下标记——input value:、anchor href:、image alt:。

常见问题

「instanceof 收窄 DOM 元素类型」能在裸 Node.js 里跑吗?

不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

核心语句

const target: Element | null = document.querySelector('.profile');
target.disabled = true;

代码示例

// 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');
}