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

Node.js环境下如何从存储HTML代码的变量中提取所有已定义ID

问题原因

原有代码会遍历所有DOM元素,无id属性的元素默认返回空字符串作为id值,全部被推入结果数组,因此出现大量空值。

优化方案

方案1:基于现有jQuery逻辑最小修改

直接通过属性选择器筛选带id的元素,同时过滤空id,无需手动遍历push:

const { JSDOM } = require( "jsdom" );
const { window } = new JSDOM( "" );
const $ = require( "jquery" )( window );

const IDs = $(myHtmlCode).find('*[id]')
  .map(function () {
    const id = this.id.trim()
    return id ? id : null
  })
  .get() // 将jQuery集合转为普通数组

方案2:直接使用JSDOM原生API(可省去jQuery依赖)

const { JSDOM } = require("jsdom");
const dom = new JSDOM(myHtmlCode);
const IDList = dom.window.document.querySelectorAll('*[id]');

const IDs = Array.from(IDList)
  .map(el => el.id.trim())
  .filter(Boolean) // 自动过滤空字符串等假值

两种方案最终得到的IDs数组仅包含非空的有效id值,不会出现冗余空字符串。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 10:57:00