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

I would like to find some specific text with jquery and replace it with an updated version, including some HTML.

I tried this one , which works 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 text + HTML to replace the target expression, it gets β€œformatted” and reads like plain text ...

Do you guys know any solution to this problem? Is it possible to add HTML to a replacement expression?

Thank.

+3
source share
2 answers

jQuery , . , node, HTML .

, , , :)

node HTML-. HTML- 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>');
}
+4

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

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

some html stuff

" );
0

Source: https://habr.com/ru/post/1757198/


All Articles