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

如何使用JavaScript读取meta标签的content属性值?

没问题,我来帮你把那段jQuery代码转换成原生JavaScript实现,完全不需要依赖jQuery库:

最直接的替代方案(和原jQuery逻辑一致)

用document.querySelector()就能直接复用你之前的CSS选择器,语法非常接近:

// 定位到目标meta标签
const priceMetaTag = document.querySelector('meta[itemprop="price"]');
// 读取content属性值,加个判断避免标签不存在时报错
const priceValue = priceMetaTag ? priceMetaTag.getAttribute('content') : null;
console.log(priceValue); // 输出结果:"175.03"

更简洁的ES6+写法(可选链操作符)

如果你的项目支持ES6及以上语法,可以用可选链?.简化判断,代码更清爽:

const priceValue = document.querySelector('meta[itemprop="price"]')?.getAttribute('content');
console.log(priceValue); // 输出结果:"175.03"

额外:转成数字类型(如果需要做计算)

如果你需要把读取到的字符串转成可用于计算的数字类型,可以用parseFloat():

const priceNumber = parseFloat(document.querySelector('meta[itemprop="price"]')?.getAttribute('content'));
console.log(priceNumber); // 输出数字类型的175.03

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:35:03