2

I want to replace text with an image using jQuery. I have been using the .replace function to replace text with more text. How would I replace the text with an html tag, like an <img> tag.

Here is my code:

function wow() {
  $('.messageBody').each(function() {
      var text = $(this).text();
      var image = '<img class = "emote" src = "trump.png">'
      $(this).text(text.replace(':trump:', image.outterHTML));
  });
}
setInterval(wow, 1000);

Here is the HTML:

<span class="messageBody">:trump:</span>
Dave Thomas
  • 3,667
  • 2
  • 33
  • 41
ariagno
  • 532
  • 1
  • 15
  • 29

3 Answers3

7

If you use .html instead of .text it will work. Change this line:

  $(this).text(text.replace(':trump:', image.outterHTML));

to this:

  $(this).html(text.replace(':trump:', image));

Note: because image is a string you don't need the .outerHTML.

If the messageBody has more than just text inside (it contains HTML) then you'll also want to change this line:

  var text = $(this).text();

to this:

  var text = $(this).html();

so the full code would be:

function wow() {
  $('.messageBody').each(function() {
      var text = $(this).html();
      var image = '<img class="emote" src="trump.png">';
      $(this).html(text.replace(':trump:', image));
  });
}
setInterval(wow, 1000);
winhowes
  • 7,845
  • 5
  • 28
  • 39
2

Can use html(function) which also will loop all instances

$('.messageBody').html(function(_, existingHtml){
    var image = '<img class = "emote" src = "trump.png">'
    return existingHtml.replace(':trump', image);
});

Using text() strips any html tags

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Thanks for this! I didn't understand how to get the code to loop every time another message appeared, Thanks bunches! – ariagno Oct 17 '16 at 01:31
1

Change your code to:

function wow() {
  $('.messageBody').each(function() {
      var text = $(this).text();
      var image = '<img class = "emote" src = "trump.png">'
      $(this).html(text.replace(':trump:', image));
  });
}
setInterval(wow, 1000);
Web Dev
  • 306
  • 3
  • 5