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

如何通过data-i18n-key获取外部应用添加的DOM元素?

无法通过data-i18n-key属性获取外部应用添加的元素怎么办?

我需要获取由外部应用动态添加的元素,唯一可用的定位标识是data-i18n-key属性。尝试用document.querySelectorAll('[data-i18n-key="sdk.seamless_product_reward.paid_items_required"]')获取,但返回结果为空。

代码示例

JavaScript代码:

const buttons = document.querySelectorAll('[data-i18n-key="sdk.seamless_product_reward.paid_items_required"]');
console.log(buttons.length);

HTML代码(外部应用动态生成):

<span class="lion-reward-item__redeem-button-text lion-loyalty-page-reward-item__redeem-button-text" data-i18n-key="sdk.seamless_product_reward.paid_items_required">Paid items required</span>

解决方法

  • 确保元素已加载完成
    外部应用动态添加的元素大概率在你的代码执行时还未渲染到DOM中,可通过以下方式处理:

    1. MutationObserver监听DOM变化(推荐生产环境使用)
      这种方式能在元素被添加到DOM时立即触发查询,无需固定延迟:
      // 监听整个文档的子节点变化,也可指定外部应用挂载的父容器缩小范围
      const observer = new MutationObserver((mutations) => {
        mutations.forEach(mutation => {
          if (mutation.addedNodes.length) {
            const targetElements = document.querySelectorAll('[data-i18n-key="sdk.seamless_product_reward.paid_items_required"]');
            if (targetElements.length > 0) {
              console.log(targetElements.length);
              observer.disconnect(); // 找到元素后停止监听,避免重复触发
            }
          }
        });
      });
      
      observer.observe(document.body, { childList: true, subtree: true });
      
    2. 延迟查询(仅测试用)
      简单设置一个延迟,给外部应用足够的渲染时间:
      setTimeout(() => {
        const buttons = document.querySelectorAll('[data-i18n-key="sdk.seamless_product_reward.paid_items_required"]');
        console.log(buttons.length);
      }, 1500); // 根据实际加载速度调整延迟时长
      
    3. 绑定外部应用的加载事件
      如果外部应用提供了加载完成的回调或自定义事件,直接在该事件触发后执行查询逻辑。
  • 检查选择器与属性值是否匹配
    在浏览器控制台执行document.querySelectorAll('[data-i18n-key]'),先确认页面中是否存在带该属性的元素,再核对属性值的大小写、特殊字符是否完全一致(你的选择器写法本身没问题,属性值里的点号不需要转义)。

  • 检查元素是否在iframe内
    如果外部应用的元素嵌入在iframe中,直接用document无法查询到,需要先获取iframe的文档对象:

    const targetIframe = document.querySelector('iframe[src*="外部应用域名"]');
    if (targetIframe?.contentDocument) {
      const buttons = targetIframe.contentDocument.querySelectorAll('[data-i18n-key="sdk.seamless_product_reward.paid_items_required"]');
      console.log(buttons.length);
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:15:16