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

如何用jQuery/Javascript为字符串字符包裹HTML标签并保留原有span类

解决方案:保留原有标签并包裹每个字符

原代码的问题在于使用$("p").text()获取内容时,会丢失所有HTML结构(包括原有的<span class="test">),导致无法保留目标标签和类名。以下是修正后的实现:

修正后的代码

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>This is a <span class="test">test</span> string</p>

CSS

span {
   border: 1px solid red;
}

span.test {
    border: 1px solid blue;
}

JavaScript

// 递归处理所有节点:包裹文本字符,保留并增强原有标签
function wrapTextNodes(node) {
  // 处理文本节点:拆分每个字符用test_new类的span包裹
  if (node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== "") {
    const chars = node.textContent.split("");
    const fragment = document.createDocumentFragment();
    chars.forEach(char => {
      const span = document.createElement("span");
      span.className = "test_new";
      span.textContent = char;
      fragment.appendChild(span);
    });
    node.parentNode.replaceChild(fragment, node);
  } 
  // 处理元素节点:先递归处理子节点,再检查是否需要添加新类
  else if (node.nodeType === Node.ELEMENT_NODE) {
    Array.from(node.childNodes).forEach(child => wrapTextNodes(child));
    if (node.tagName === "SPAN" && node.classList.contains("test")) {
      node.classList.add("test_new");
    }
  }
}

// 启动处理
wrapTextNodes($("p")[0]);

效果说明

  1. 所有字符(包括原有<span class="test">内部的字符)都会被<span class="test_new">包裹
  2. 原有的<span class="test">会被保留,并新增test_new类
  3. 带有test类的span会显示蓝色边框(符合CSS优先级规则),其他span显示红色边框

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 18:32:56