Find text(A) and replace it with text(B) + HTML

2019-07-07 04:24发布

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.

2条回答
做个烂人
2楼-- · 2019-07-07 04:56

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>');
}
查看更多
何必那么认真
3楼-- · 2019-07-07 05:16

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

changed to

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

some html stuff

");

查看更多
登录 后发表回答