0

I confused and i need your help how? If

<pre>Lorem Ipsum Dolor Sir amet</pre>

and i want the "ipsum" text colored yellow.

3 Answers3

3

Try to create a span tag and wrap your content in that.

$('pre:contains(Ipsum )').each(function(){
  $(this).html(
    $(this).html().replace('Ipsum ','<span class="colorClass">  Ipsum  </span>')
  );
});

Working Demo

Suresh Atta
  • 118,038
  • 37
  • 189
  • 297
2

you can't highlight a text node, you need to wrap it in another element like span then use it to apply the highlight

$('pre').html(function(idx, html){
    return html.replace(/(Ipsum)/, '<span class="highlight">$1</span>')
})

Demo: Fiddle

Arun P Johny
  • 376,738
  • 64
  • 519
  • 520
1

Run a little replace function to programmatically isolate your target word, in this case the second word. You could also substitute this for a hardcoded value should you always know what word you are targeting.

HTML

<pre>Lorem Ipsum Dolor Sir amet</pre>

CSS

span { background: yellow; }

jQuery

$('pre').html(function(i, word) {
  return word.replace(/\s(.*?)\s/, ' <span>$1</span> ');
});

Codepen example

kunalbhat
  • 1,664
  • 10
  • 11