1

What I'm trying to do is to force this code to replace a part of the text that is ':•:' if he finds it on the page in a paragraph, with an image.

$("p").each(function () { 
    if ($(this).children().length == 0) {
        $(this).text($(this).text().replace(':•:').html('<img src = "http://lilpic.png" />')); 
    } 
});

But what I ended up with was that the text was indeed replaced, but not with the image as it is, but with just ugly raw HTML-code of it. What am I doing wrong? What I need in the end is just a code, that would change the marker ':•:' into a picture.

tshimkus
  • 1,173
  • 2
  • 17
  • 24
  • Possible duplicate of [jquery replace matching text with html](https://stackoverflow.com/questions/34598048/jquery-replace-matching-text-with-html) – Heretic Monkey Feb 02 '19 at 01:11

1 Answers1

0

To achieve the desired result:

  • use .html() instead of .text() to set the html. (Remember, it's no longer just text.)
  • use .replace(':•:', '<img src="http://lilpic.png" />') instead of .replace(':•:').html('<img src = "http://lilpic.png" />')

Note: the image is not going to show up. (Because http://lilpic.png is not a link to an image.

$("p").each(function() {

  if ($(this).children().length == 0) {
    $(this).html($(this).text().replace(':•:', '<img src="http://lilpic.png" />'));
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<p>Hello, this is some text :•:</p>

Also, there are some other improvements you can make to your code listed below.

$("p").each(function() {
  // Use $(this) instead of $(this), as it's faster
  var $this = $(this);

  if ($this.children().length == 0) {
    //Replace ':•:' with an image and store it in a variable called `newText`
    var $newText = $this.text().replace(':•:', '<img src="http://lilpic.png" />');

    //Set the new text with the replace image
    $this.html($newText);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Hello, this is some text :•:</p>

<p>Hello, this is some text :•:</p>
Chris Happy
  • 7,088
  • 2
  • 22
  • 49
  • You are a wizard! Thank you so much, it works now. For some reason, when I tried this last time, it didn't work. Maybe I made a mistake somewhere. – Sensitive Sirin Feb 02 '19 at 00:58