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

选中嵌套div内第二个子div的SVG时JS报错,如何解决并替换为自定义图片?

问题解决:替换指定嵌套div中的SVG为自定义图片

错误原因分析

  • getElementsByClassName(".bpa-front-pm-pay-local-icon") 参数多了前缀.,类名应直接写bpa-front-pm-pay-local-icon
  • getElementsByClassName 返回的是元素集合,不能直接访问.style,需通过索引[0]获取单个元素

修正后的完整代码

setTimeout(function() {
  // 精准定位目标容器:.bpa-front--pm-body-items下的第二个.bpa-front-module--pm-body__item
  const targetContainer = document.querySelector(".bpa-front--pm-body-items .bpa-front-module--pm-body__item:nth-child(2)");
  if (!targetContainer) return; // 避免找不到元素时报错

  // 获取要隐藏的SVG
  const targetSvg = targetContainer.querySelector(".bpa-front-pm-pay-local-icon");
  if (targetSvg) {
    targetSvg.style.display = 'none'; // 隐藏原SVG

    // 创建自定义图片元素
    const customImg = document.createElement('img');
    customImg.src = '你的自定义图片URL'; // 替换为你的图片地址
    customImg.className = 'bpa-front-pm-pay-local-icon'; // 复用原SVG类名保持样式一致
    customImg.style.width = '48px'; // 和原SVG尺寸匹配

    // 将图片插入到p标签之前
    const pTag = targetContainer.querySelector('p');
    if (pTag) {
      targetContainer.insertBefore(customImg, pTag);
    }
  }
}, 5000);

代码说明

  • 用querySelector精准定位目标容器,避免依赖索引的不稳定问题
  • 增加元素存在性判断,防止DOM未加载完全引发报错
  • 创建图片元素并继承原SVG样式,保证视觉一致性
  • 通过insertBefore将图片插入到指定位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:54:52