I have the following HTML.
<p><img src="myimage.jpg" />This is my text</p>
And the following javascript to replace the spaces with Non-breaking spaces. This works fine except for the fact that it removes the image.
$("div.myDiv p").each( function() {
$(this).text( $(this).text().replace(/ /g, '\xA0'));
});
Any ideas how I can replace the spaces in the text and not alter the image.?
You need to check for the nodeType and replace only this value:
$(function() {
$("p").contents().each(function(i, e) {
if( e.nodeType === 3 ) {
e.nodeValue = e.nodeValue.replace(/ /g, '\xA0')
}
});
});
Example: http://www.jsfiddle.net/4yUqL/42/
No JavaScript needed for this.
<p><img src="myimage.jpg" />This is my text</p>
and in CSS
div.myDiv p {
white-space: nowrap;
}
Depending on your document structure, it might be useful to add an extra imgAndCaption
CSS class to your paragraphs where needed, and do:
p.imgAndCaption {
white-space: nowrap;
}
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