如何用jQuery为段落内单词包裹<span>标签同时保留DOM中的<strong>标签
解决保留
<strong>标签同时为单词包裹<span>的问题 你的问题出在使用text()方法提取内容——这个方法会把元素里的所有HTML结构都丢弃,只取纯文本,所以<strong>标签自然就没了。要同时保留原有HTML结构(比如<strong>)和为每个单词包裹<span>,我们需要遍历文本节点而非直接提取整个元素的文本,具体方案如下:
修改后的jQuery代码
$(document).ready(function() { $("p").each(function() { // 遍历当前<p>下的所有子节点(包括文本节点和元素节点) $(this).contents().each(function() { // 只处理非空的文本节点(nodeType === 3 代表文本节点) if (this.nodeType === 3 && $.trim(this.nodeValue) !== '') { // 拆分文本为单词数组 const words = $.trim(this.nodeValue).split(' '); const newNodes = []; words.forEach((word, index) => { // 为每个单词创建带outline类的span const span = $('<span class="outline"></span>').text(word); newNodes.push(span[0]); // 单词之间保留空格(最后一个单词后不加) if (index !== words.length - 1) { newNodes.push(document.createTextNode(' ')); } }); // 用新的节点集合替换原文本节点 $(this).replaceWith(newNodes); } }); }); });
代码思路说明
- 用
contents()替代text():contents()会获取元素内的所有子节点,包括<strong>这类元素节点和纯文本节点,这样就能保留原有HTML结构。 - 只处理文本节点:通过
nodeType === 3判断当前节点是文本节点,同时跳过空文本节点(避免处理多余的空白)。 - 保留单词间距:拆分单词后,手动添加空格文本节点,确保排版和原内容一致。
- 替换节点而非覆盖HTML:用
replaceWith()把单个文本节点替换为span节点+空格节点的组合,不会影响其他元素节点(比如<strong>)。
完整示例(含CSS和HTML)
<!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style> /* 外部单词的span样式 */ span.outline { color: blue; } /* 保留strong标签内的红色样式 */ strong span.outline { color: red; } </style> </head> <body> <p>We invest with <strong>capital,</strong></p> <p><strong>know-how, experience</strong></p> <p><strong>and ambition.</strong></p> <script> $(document).ready(function() { $("p").each(function() { $(this).contents().each(function() { if (this.nodeType === 3 && $.trim(this.nodeValue) !== '') { const words = $.trim(this.nodeValue).split(' '); const newNodes = []; words.forEach((word, index) => { const span = $('<span class="outline"></span>').text(word); newNodes.push(span[0]); if (index !== words.length - 1) { newNodes.push(document.createTextNode(' ')); } }); $(this).replaceWith(newNodes); } }); }); }); </script> </body> </html>
这个方案会完美保留原有的<strong>标签,同时不管是<strong>内部还是外部的单词,都会被<span class="outline">包裹,样式也能按照预期生效~
内容的提问来源于stack exchange,提问作者Giorgi Khatchapuridze
相关产品推荐
相关产品推荐

