HTML preview showing the first element

1

I made this html preview, it works fine for my purpose however the first element is appearing as text, and this is a bad result, I understand very little of jquery and javascript, I'm starting to study, I'd like to understand the is going wrong. If you put <div></div> the opening tag appears: <div> , but only the first, the rest of the code does not appear
Run the snippet to better understand

function showPreview()
{
  var value = $('#copy').val().trim();
  value = value.replace("<", "&lt;");
  value = value.replace(">", "&gt;");
  $('#preview').html(value);
}
textarea {
resize:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><textareaid="copy" onInput="showPreview();"><div><img src='https://i.imgur.com/FfInIT9.jpg' width='100'/></div>
</textarea>
<br>
<div id="preview"/>
    
asked by anonymous 07.07.2018 / 23:10

2 answers

0

You need to change the function and change your id preview. So the htmls tags you enter will be interpreted as such.

function showPreview()
{
 var value = $('#copy').val().trim();
 $('#preview').html(value);
}

<div id="preview"> </div>

I hope I have helped.

    
07.07.2018 / 23:34
0

This is because you are giving replace , but inserting the character again, so it shows the first character. You must leave it empty, so the characters do not appear:

  

The regular expression: /</g inside replace is so that whenever and > are found in the text if there is nothing.

function showPreview()
{
  var value = $('#copy').val().trim();
  value = value.replace(/</g, "");   // vazio
  value = value.replace(/>/g, "");   // vazio
  $('#preview').html(value);
}
textarea {
  resize:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><textareaid="copy" onInput="showPreview();">
</textarea>
<br>
<div id="preview"></div>
    
07.07.2018 / 23:30