jQuery:使用一些元素查找并包装textnode

前端之家收集整理的这篇文章主要介绍了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相关文章