3

I'd like to find with jquery some specific text, and replace it with a renewed version including some HTML.

I've tried this, which is working when I use only text:

<script type="text/javascript" >
    jQuery(document).ready(function(){
       
    jQuery("*").contents().each(function() {
    if(this.nodeType == 3)
    this.nodeValue = this.nodeValue.replace("hello mum", "bye bye mum");
    });
            
    })
</script>

However, if I add some text + HTML to replace the targeted expression, it gets "formatted" and is read as plain text...

Do you know guys some solution to this problem? Can I add HTML to the replacing expression?

Thanks.

Community
  • 1
  • 1
Peanuts
  • 2,641
  • 6
  • 29
  • 34
  • Another solution found here: https://stackoverflow.com/questions/23759703/jquery-find-text-and-replace-with-html – Peanuts Dec 31 '22 at 11:56

2 Answers2

4

jQuery is a little problematic when it comes to text nodes. Also, since you are directly manipulating the contents of a text node, all HTML will be considered as text.

The simplest solution I can think of is a little hacky, but works great :)

Replace the text node with a dummy HTML element. Then replace that dummy HTML element with your replacement HTML.

var isTextNode = this.nodeType == 3;
var matchesText = this.nodeValue.indexOf('hello mum') > -1;

if(isTextNode && matchesText) {
    // replace text node with dummy element
    // so jQuery can be used
    var dummy = $('<b>');
    this.parentNode.replaceChild(dummy[0], this);

    dummy.replaceWith('my <b>awesome</b> html now <i>works</i>');
}
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • Don't forget your `> -1` for the `.indexOf()` in case the text is at index `0`. :o) EDIT: Also `this.nodeType = 3` should be `this.nodeType == 3` – user113716 Jul 29 '10 at 18:40
0

this.nodeValue = this.nodeValue.replace("hello mum", "bye bye mum");

changed to

this.nodeValue = this.nodeValue.replaceWith("hello mum", "

some html stuff

");
Chris
  • 11,780
  • 13
  • 48
  • 70
  • this is what I tried, but the second part is literally output, even if they are some HTML tags, they will be read by the visitor – Peanuts Jul 29 '10 at 18:06