Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 296
Abhinav Pandey Avatar asked Oct 08 '11 17:10

Abhinav Pandey


People also ask

What is nodeValue in HTML?

The nodeValue property sets or returns the value of a node. If the node is an element node, the nodeValue property will return null.

How do you insert text in node?

Alternatively, you can add a text node by clicking the New Template Node icon or by right-clicking in the template view and selecting Add New Item from the context menu. A node labeled "Text" is displayed in the template view below the other node.

What is nodeValue in JS?

Value. A string containing the value of the current node, if any. For the document itself, nodeValue returns null . For text, comment, and CDATA nodes, nodeValue returns the content of the node. For attribute nodes, the value of the attribute is returned.


1 Answers

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/

like image 177
James Montagne Avatar answered Sep 30 '22 11:09

James Montagne