5

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?

2 Answers 2

11

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/

Sign up to request clarification or add additional context in comments.

Comments

1

Your problem is that you're inserting the HTML into a text node (and it's therefore being treated as text). Instead of replacing _link_ with <a href="http://google.com">Google</a>, you'd want to take the text node, remove the text from _link_ onward, append an HTML node (that contains the anchor) and put all of text after _link_ into a new text node following that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.