You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中使用jsdom.getElementById始终返回undefined的问题

问题分析与解决方法

你的核心错误是误解了getElementById()的作用:这个方法只能根据元素的id属性值查找元素,而你用的//title、h1、title这些要么是XPath表达式,要么是标签名,根本不是元素的id,所以必然返回null。

正确的获取方式分以下几种情况:

  • 获取<title>元素:可以用querySelector()(支持CSS选择器),或者直接用doc.title快速获取标题文本
  • 获取<h1>元素:同样用querySelector('h1'),或者getElementsByTagName('h1')[0](注意这个方法返回集合,需取第一个元素)
  • 如果一定要用getElementById():需要先给目标元素添加id属性,比如给<h1>加上id="main-title",再用doc.getElementById('main-title')查找

修改后的代码示例:

import { JSDOM } from 'jsdom';
const htmlContent = `<!DOCTYPE html><html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Hello World Title</title>
</head>
<body>
    <h1 id="main-heading">Hello World Body</h1>
</body>
</html>`;

const dom = new JSDOM(htmlContent);
const doc = dom.window.document;

// 获取title元素及文本
const titleElem = doc.querySelector('title');
console.log('title元素:', titleElem);
console.log('title文本:', doc.title);

// 通过id获取h1元素及文本
const h1Elem = doc.getElementById('main-heading');
console.log('h1元素:', h1Elem);
console.log('h1文本:', h1Elem.textContent);

内容的提问来源于stack exchange,提问作者Jeremy Woodland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 22:32:38