TypeScript与DOM操作:深入理解相关类型及实战示例

TypeScript与DOM操作:深入理解相关类型及实战示例

基础类型介绍

Document

代表整个文档的根节点。它是所有DOM操作的起点。

示例

typescript 复制代码
const docTitle = document.documentElement.title; // 获取文档标题
document.title = "新标题"; // 设置文档标题

Element

表示一个DOM元素,是所有元素节点的基类。

示例

typescript 复制代码
const element = document.createElement("div"); // 创建一个新的div元素

HTMLElement

继承自Element,特指HTML元素,提供了针对HTML元素的特定属性和方法。

示例

typescript 复制代码
const div = document.createElement("div") as HTMLElement;
div.style.backgroundColor = "blue"; // 设置样式

NodeListHTMLCollection

  • NodeList:表示一组节点的集合,通常由querySelectorAll返回。
  • HTMLCollection:与NodeList相似,但特指HTML元素集合,通常由getElementsByTagName等方法返回。

示例

typescript 复制代码
const allDivs = document.querySelectorAll("div"); // NodeList
const firstDivs = document.getElementsByTagName("div"); // HTMLCollection

EventTarget

所有能触发事件的对象都实现了这个接口,包括ElementDocument等。

示例

typescript 复制代码
document.addEventListener("click", (event: Event) => {
    console.log("Clicked!");
});

扩展类型与自定义属性

接口扩展

TypeScript允许通过接口扩展来增强现有类型,这对于给DOM元素添加自定义属性非常有用。

示例

typescript 复制代码
interface HTMLElement {
    customAttribute: string;
}

document.body.customAttribute = "Custom Value";
console.log(document.body.customAttribute); // 输出: Custom Value

类型断言与非空断言

在处理DOM选择时,常需使用类型断言或非空断言来确保类型安全。

示例

typescript 复制代码
const myDiv = document.getElementById("myDiv") as HTMLDivElement;
// 或
const safeDiv = document.getElementById("myDiv")!; // 确信此元素存在

实战技巧

利用泛型获取精确元素类型

使用querySelectorquerySelectorAll时,可以通过泛型指定预期的元素类型。

示例

typescript 复制代码
const header = document.querySelector("header") as HTMLElement;
const paragraphs = document.querySelectorAll("p") as NodeListOf<HTMLParagraphElement>;

安全的事件处理

为事件处理器指定精确的事件类型,提高代码的可读性和安全性。

示例

typescript 复制代码
document.getElementById("myButton")!.addEventListener("click", (event: MouseEvent) => {
    const button = event.target as HTMLButtonElement;
    console.log(button.textContent);
});
相关推荐
崔庆才丨静觅5 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60616 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了6 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅6 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅6 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅7 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment7 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅7 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊7 小时前
jwt介绍
前端
爱敲代码的小鱼7 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax