"jQuery way" replace only node text with a combination of HTML and text?

In my userscript web browser project, I need to replace only one node text without affecting other HTML elements under the same node parent as text. And I need to replace it with more than one node:

<div id="target"> foo / bar; baz<img src="/image.png"></div> 

Need to become:

 <div id="target"> <a href="#">foo</a> / <a href="#">bar</a>; <a href="#">baz</a><img src="/image.png"></div> 

I know jQuery does not have much support for text nodes. I know that instead of jQuery I could use direct DOM calls. And I know that I can just do something like $('#target').html( my new material + , which I don't want to change ) . Also note that I would like to keep the initial space, this in itself seems complicated.

What I would like to ask the experts here, Is there any idiomatic jQuery way for this?

+5
source share
3 answers

Basically you want to replace the first child (text node) with new content. You need http://api.jquery.com/replaceWith/

 // Text node we want to process and remove var textNode = $("#target").contents().first(); // Break the text node up var parts = textNode.text().split(/\s/); // Put links around them var replaceWith = ""; for (var i =0; i < parts.length;i++) { replaceWith += "<a href='http://www.google.com'>" + escapeHTML(parts[i]) + "</a> "; } // Replace the text node with the HTML we created textNode.replaceWith(replaceWith); function escapeHTML(string) { return string.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="target">example, handles escaping properly, you should see an ampesersand followed by "amp;" here: &amp;amp; <img src="/foobar.png"></div> 

http://jsfiddle.net/NGYTB/1/

+9
source

Try this approach

 // nodeType = 1 corresponds to element node // You are filtering everything out other than that and // removing the textnodes from it.. // contents() will get everything including the text ​$('#target'​).contents().filter(function() { return this.nodeType != 1; }).remove(); // Then you are prepending the div with the html that needs to // replaced with the text... $('#target').prepend('<a href="#">mixed</a> text <a href="#">and</a> HTML'); // This makes sure you do not touch the initial img element inside the div 

You can add other types of nodes if you do not want to delete certain types of nodes CHECK FIDDLE

+1
source

try this version ..

 $('#target').html('<a href="#">mixed</a> text <a href="#">and</a> HTML' + $('#target').html()); 
0
source

Source: https://habr.com/ru/post/1439289/


All Articles