views:

80

answers:

2

Hello guys,

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.

A: 

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

changed to

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

some html stuff

");

Chris
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
+1  A: 

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
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`
patrick dw
@patrick - thanks :) fixed those issues.
Anurag