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

动态按钮文本变更后获取cost值在Chrome报错的技术问题

问题:动态变更按钮的cost值获取失败

按钮元素结构

变更前

<button _ngcontent-wex-c70="" 
    class="btn btn-wait buy font-family-title height-70 pp-sun-ins"><label _ngcontent-wex-c70="" translate="" 
    class="font-family-title label">BUY</label>
</button>

变更后

<button _ngcontent-wex-c70="" 
    class="btn btn-root press font-family-title pp-sun-ins"><span _ngcontent-wex-c70="" 
    class="d-power power-column justify-content-center align-items-center"><label _ngcontent-wex-c70="" translate="">EXIT NOW</label><label _ngcontent-wex-c70="" 
    class="price"><span _ngcontent-wex-c70="" 
    class="cost">1.46</span><i _ngcontent-wex-c70="" 
    class="UNT"></i></label></span>
</button>

尝试的代码

var cost = document.getElementsByClassName("cost")[0].innerText;
console.log("my cost is: "+cost)

问题现象

  • 上述代码在在线JavaScript测试工具中可正常运行
  • 在Chrome浏览器控制台执行时,返回错误:
Uncaught TypeError: Cannot read properties of undefined (reading 'innertext')
  • 已通过开发者工具元素面板确认变更后的元素存在,但执行代码仍报错

解决办法

  1. 修正大小写错误
    JavaScript是大小写敏感语言,错误提示中显示读取的是innertext(小写t),但标准API是innerText(大写T)。检查你实际执行的代码是否写错了大小写,修正后代码如下:
var cost = document.getElementsByClassName("cost")[0].innerText;
console.log("my cost is: "+cost);
  1. 确认元素上下文
  • 执行代码时确保元素所在的浏览器标签页处于激活状态,不要在其他标签页操作控制台
  • 先打印元素集合,确认是否能获取到目标元素:
    console.log(document.getElementsByClassName("cost"));
    
    如果输出为空数组,说明元素可能嵌套在iframe内,需先获取iframe的文档对象再查找:
    // 替换为实际的iframe选择器
    var iframe = document.querySelector('iframe');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
    var costElement = iframeDoc.getElementsByClassName("cost")[0];
    if(costElement) {
        console.log("my cost is: "+costElement.innerText);
    }
    
  1. 使用可选链避免报错
    添加可选链操作符?.,即使元素不存在也不会抛出错误,而是返回undefined:
var cost = document.getElementsByClassName("cost")[0]?.innerText;
console.log("my cost is: "+ (cost || '未找到目标元素'));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:55:16