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

使用node-html-parser无法读取input元素value属性值的解决方法

问题

我正在使用node-html-parser模块进行HTML解析,目标HTML为:

<div><input type="hidden" value="199,9" ></div>

编写的代码如下:

var { parse }   = require('node-html-parser'); 
const body = '<div><input type="hidden" value="199,9" ></div>' 
var dom  = parse(body) 
console.dir(dom.querySelectorAll('div input')[0]); 
console.log(`log from  ` + dom.querySelectorAll('div input')[0] ); 
console.log(`log from value ` + dom.querySelectorAll('div input')[0].value );

执行后输出为:

log from <input type="hidden" value="199,9" > 
log from value undefined

调用.value属性返回undefined,我只想使用node-html-parser模块,该如何解决此问题?

补充:执行console.dir(dom.querySelectorAll('div input')[0])后,能看到rawAttrs字段包含value属性,但我不确定该模块是否支持单独选择属性,考虑用正则处理。

解决方案

node-html-parser的元素对象并不直接通过.value获取属性值,模块本身提供了更直接的属性操作方式,无需用正则处理:

  • 使用getAttribute()方法获取指定属性:

    const input = dom.querySelectorAll('div input')[0];
    console.log(`log from value ` + input.getAttribute('value')); // 输出 199,9
    
  • 直接访问元素的attrs属性(该属性是包含所有标签属性的对象):

    const input = dom.querySelectorAll('div input')[0];
    console.log(`log from value ` + input.attrs.value); // 输出 199,9
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:12:05