Javascript - replace text but don't change image in p tag
I have the following HTML.
<p><img src="myimage.jpg" />This is my text</p> And the following javascript to replace spaces with non-breaking spaces. This works great, except that it deletes the image.
$("div.myDiv p").each( function() { $(this).text( $(this).text().replace(/ /g, '\xA0')); }); Any ideas how I can replace spaces in the text and not change the image.
You need to check for 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/
JavaScript is not needed for this.
<p><img src="myimage.jpg" />This is my text</p> and in CSS
div.myDiv p { white-space: nowrap; } Depending on the structure of your document, it may be useful to add an additional imgAndCaption CSS class to your paragraphs where necessary, and follow these steps:
p.imgAndCaption { white-space: nowrap; } The image tag is destroyed because the img tag is not enabled using text() , so I suggest you save the image first and add it after replacement
$("div.myDiv p").each( function() { var $img = $(this).find('img:first'); $(this).text( $(this).text().replace(/ /g, '\xA0')); $(this).prepend($img) ; });