This is my text

And the ...">

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.

+4
source share
4 answers

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/

+8
source

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; } 
+2
source

Why not put the text in the div and change the text in the div, i.e.

 <p><img src="myimage.jpg" /><div>This is my text</div></p> $("div.myDiv p div").each( function() { $(this).text( $(this).text().replace(/ /g, '\xA0')); }); 
+1
source

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) ; }); 
+1
source

Source: https://habr.com/ru/post/1335224/


All Articles