1

my HTML code :

<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>

I want to find any "firebrand" inside the body and replace it with <span class="firebrand">firebrand</span> with jQuery

karim79
  • 339,989
  • 67
  • 413
  • 406
mdennisa
  • 177
  • 2
  • 13
  • Please articulate your intention more clearly. As you can see in the answer of Karim79 the specification isn't clear enough. – Huppie Nov 24 '09 at 09:46
  • sorry my bad, I just want to find any keyword I desire to be wrapped with span regardless the parent element, it should search in the whole document. I need to get the text node and wrap it up with span, so I can give a different style. is there anyway I can do this without using $(selector).html() ?? – mdennisa Nov 24 '09 at 14:35

2 Answers2

4

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"));
David Tang
  • 92,262
  • 30
  • 167
  • 149
0

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'));
msmithgu
  • 340
  • 1
  • 5