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);
});
相关推荐
颜渊呐1 分钟前
uniapp中APPwebview与网页的双向通信
前端·uni-app
10年前端老司机13 分钟前
React 受控组件和非受控组件区别和使用场景
前端·javascript·react.js
夏晚星14 分钟前
vue实现微信聊天emoji表情
前端·javascript
停止重构16 分钟前
【方案】前端UI布局的绝技,响应式布局,多端适配
前端·网页布局·响应式布局·grid布局·网页适配多端
極光未晚16 分钟前
TypeScript在前端项目中的那些事儿:不止于类型的守护者
前端·javascript·typescript
ze_juejin17 分钟前
Vue3 + Vite + Ant Design Vue + Axios + Pinia 脚手架搭建
前端·vue.js
Rrvive18 分钟前
原型与原型链到底是什么?
javascript
lichenyang45319 分钟前
React项目(移动app)
前端
用户618482402195120 分钟前
Vue-library-start,一个基于Vite的vue组件库开发模板
前端
美团技术团队32 分钟前
报名 | 美团技术沙龙第86期:多业务场景下,美团如何做性能优化
前端