"jQuery way" to replace just a text node with a mix of HTML and text?
You basically want to replace the first child (text node) with the 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, "&").replace(/</g, "<").replace(/>/g, ">");
}
<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 ampersand followed by "amp;" here: &amp; <img src="/foobar.png"></div>
http://jsfiddle.net/NGYTB/1/