In my web browser userscript project I need to replace just one text node without affecting the other HTML elements under the same parent node as the text. And I need to replace it with more than one node:
<div id="target"> foo / bar; baz<img src="/image.png"></div>
Needs 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 doesn't have a whole lot of support for text nodes. I know I could use direct DOM calls instead of jQuery. And I know I could just do something like $('#target').html(
my new stuff +
stuff I don't want to change)
. Also note that I'd like to preserve the initial space, this on its own seems to be tricky.
What I'd like to ask the experts here is, Is there a most idiomatic jQuery way to do this?
Try this approach
You can add other node types if you do not want to remove specific nodetypes CHECK FIDDLE
try this..edited version
You basically want to replace the first child (text node) with the new content. You need http://api.jquery.com/replaceWith/
http://jsfiddle.net/NGYTB/1/