Given a string of text that is both adjacent to a span and inside of a div, what are some methods to modify just that text, leaving the surrounding HTML intact? For example:
<div id="my-div">modify this text<span id="my-span"></span></div>
I have tried things like
$('#my-div').html(function(i, elem){blah;});
but this seems to cause the span to be deleted and a new span to be added (I notice that some styling is lost on the span).
I realize that it would be best to wrap the text string in its own HTML tags before applying client-side code, but that is out of my control.
This seems to work:
$('#my-div').contents()
.filter(function() { return this.nodeType == 3; })
.replaceWith('new text or html');
nodeType == 3 is to test for a text node.
What about using jQuery's contents()
method?
http://api.jquery.com/contents/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With