add HTML to text node extracted via node.nodeValue

前端 未结 2 606
我寻月下人不归
我寻月下人不归 2020-12-06 13:43

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:

相关标签:
2条回答
  • 2020-12-06 14:29

    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/

    0 讨论(0)
  • 2020-12-06 14:34

    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.

    0 讨论(0)
提交回复
热议问题