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);
});
相关推荐
lijun_xiao20091 小时前
前端最新Vue2+Vue3基础入门到实战项目全套教程
前端
90后的晨仔1 小时前
Pinia 状态管理原理与实战全解析
前端·vue.js
杰克尼1 小时前
JavaWeb_p165部门管理
java·开发语言·前端
EndingCoder1 小时前
WebSocket实时通信:Socket.io
服务器·javascript·网络·websocket·网络协议·node.js
90后的晨仔1 小时前
Vue3 状态管理完全指南:从响应式 API 到 Pinia
前端·vue.js
90后的晨仔1 小时前
Vue 内置组件全解析:提升开发效率的五大神器
前端·vue.js
我胡为喜呀2 小时前
Vue3 中的 watch 和 watchEffect:如何优雅地监听数据变化
前端·javascript·vue.js
我登哥MVP2 小时前
Ajax 详解
java·前端·ajax·javaweb
非凡ghost2 小时前
Typora(跨平台MarkDown编辑器) v1.12.2 中文绿色版
前端·windows·智能手机·编辑器·软件需求
馨谙3 小时前
/dev/null 是什么,有什么用途?
前端·chrome