jQuery : find and wrap textnode with some element

标签 jquery textnode

我的 HTML 代码:

<body>Firebrand will tend to burn any bricks out there. so the best idea is to ignore any active firebrand if you are a bricks. Otherwise, you can challenge a firebrand if you have the proper quality to keep up with their latest technology. And don't mess up with firebrand if you are a robber.</body>

我想找到体内任何“煽动者”并将其替换为 <span class="firebrand">firebrand</span>使用 jQuery

最佳答案

只需在 DOM 中递归,同时使用:

.replace(/(firebrand)/gi, '<span class="firebrand">$1</span>')

在每个文本内容上。

function firebrand($el) {
   $el.contents().each(function () {

       if (this.nodeType == 3) { // Text only
           $(this).replaceWith($(this).text()
               .replace(/(firebrand)/gi, '<span class="firebrand">$1</span>'));
       } else { // Child element
           firebrand($(this));
       }

   });
}

firebrand($("body"));

关于jQuery : find and wrap textnode with some element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1788939/

相关文章:

javascript - 在(目标)div 内居中 spin.js 微调器

javascript - 我究竟该如何编写回调函数来更改 AJAX 中的全局变量以用于 jquery?

jquery - 如何隐藏子菜单后面的 slider 按钮?

JavaScript:如何从一个元素的所有后代获取文本,而不考虑脚本?

javascript - jQuery 选择并包装 textNode

javascript - jQuery,通过单击选择一个元素

当我放在正文之前时,Javascript 不工作,但在标题中工作

java dom getTextContent() 问题

javascript - 什么是文本节点及其用途?//document.createTextNode()

css - 隐藏元素中的文本节点,但不隐藏子节点