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

时间:2009-11-24 09:31:27

标签: 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>

我想在身体内找到任何“firebrand”,并用<span class="firebrand">firebrand</span>替换为jQuery

2 个答案:

答案 0 :(得分:4)

在使用:

时,只需通过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"));

答案 1 :(得分:0)

尝试以下内容。

var textApply;
textApply = function(node){
  jQuery.map($(node), function(node) {
    var value = $(node)[0];
    if (value.nodeType == 3 && value.textContent.match(/firebrand/gi)) {
      var foo = value.textContent.replace(/[\n\r\t ]+/,' ').replace(/firebrand/gi, '<span style="color:red">Firebrand</span>');
      var newitem = $(foo);
      $(node).replaceWith(newitem);
    } else if (value.nodeName != 'SCRIPT') {
      jQuery.map($(node).contents(), textApply);
    }
  });
};
textApply($('body'));