Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - replace text but not alter image within p tag

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.?

like image 720
Tom Avatar asked Dec 16 '22 18:12

Tom


2 Answers

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/

like image 164
jAndy Avatar answered Dec 19 '22 07:12

jAndy


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;
}
like image 30
Tomalak Avatar answered Dec 19 '22 08:12

Tomalak