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

如何使用Vanilla JavaScript按类匹配替换目标元素文本为对应源元素文本

实现方案

核心思路

  • 预构建SO编号到客户名称的映射字典,避免多次遍历DOM查询,提升执行效率
  • 遍历所有待替换的td元素,匹配对应SO编号的文本完成批量替换
  • 逻辑默认包裹在DOM加载完成事件中,避免提前执行找不到目标元素的问题

完整实现代码

document.addEventListener('DOMContentLoaded', function() {
    // 构建SO编号对应客户名称的映射表
    const customerMap = {};
    const sourceNodes = document.querySelectorAll('#source-elements .sourcetext');
    sourceNodes.forEach(node => {
        // 从类名中提取SO-xxxx格式的编号
        const soCode = Array.from(node.classList).find(className => className.startsWith('SO-'));
        if (soCode) {
            customerMap[soCode] = node.textContent.trim();
        }
    });

    // 批量替换表格中td的文本内容
    const targetTds = document.querySelectorAll('table.sales-shipments td.replacetext');
    targetTds.forEach(td => {
        const soCode = Array.from(td.classList).find(className => className.startsWith('SO-'));
        // 仅当映射表中存在对应值时执行替换
        if (soCode && customerMap[soCode]) {
            td.textContent = customerMap[soCode];
        }
    });
});

兼容性说明

以上代码为纯原生JavaScript实现,支持所有现代浏览器以及IE9及以上版本,无需引入任何第三方依赖。

内容的提问来源于stack exchange,提问作者T.Newton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:45:03