Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

javascript - add HTML to text node extracted via node.nodeValue

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

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

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...