Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I wanted to know if there's any way I could output HTML after extracting contents() and performing a replace on all of the text-nodes in it.

jsFiddle: http://jsfiddle.net/bikerabhinav/t8835/1/

HTML:

<div id="msg">
    Hi, this is a Textnode _link_<br>
    this is Textnode number 2
    <br /><a href="http://google.com">element node</a>
</div>

JS:

$('#msg').contents().each(function() {
    if(this.nodeType == 3) {
        var u = this.nodeValue;
        var reg = /_link_/g;
        this.nodeValue = u.replace(reg,'<a href="http://google.com">Google</a>');
    }
});

OUTPUT:

Hi, this is a Textnode <a href="http://google.com">Google</a>
this is Textnode number 2 
element node

What I need:

Hi, this is a Textnode <a href="http://google.com">Google</a><br> <!-- as a HTML link -->
this is Textnode number 2 <br>
element node

PS:

  • I'm deliberately NOT using html() to get the contents, perform a .replace, and then use html() again to set the value because the original application which uses this snippet has complex structure (i.e. both the DOM element on which it will run, plus the string to be matched and replaced, there are over 30 expressions which need to be searched for and replaced, all are special character, like smiley codes).

    However, only text-nodes in the DOM has the string which is to be replaced, and keeping the outer html structure and elements is necessary.

The above code works, it's just not in HTML. Is there a way to achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
410 views
Welcome To Ask or Share your Answers For Others

1 Answer

If I'm understanding you correctly, I believe this will do:

$('#msg').contents().each(function() {
    if(this.nodeType == 3) {
        var u = this.nodeValue;
        var reg = /_link_/g;
        $(this).replaceWith(u.replace(reg,'<a href="http://google.com">Google</a>'));
    }
});

http://jsfiddle.net/t8835/2/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...