jQuery : find and wrap textnode with some element

拜拜、爱过 提交于 2019-11-28 11:49:26

Just recurse through the DOM, while using:

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

on each text content.

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"));

Try out the following.

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'));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!