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);
});
相关推荐
人工智能训练师3 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny073 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy4 小时前
css的基本知识
前端·css
昔人'4 小时前
css `lh`单位
前端·css
前端君5 小时前
实现最大异步并发执行队列
javascript
Nan_Shu_6146 小时前
Web前端面试题(2)
前端
知识分享小能手6 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队7 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光7 小时前
css之一个元素可以同时应用多个动画效果
前端·css
萌萌哒草头将军7 小时前
Oxc 和 Rolldown Q4 更新计划速览!🚀🚀🚀
javascript·vue.js·vite