HTML preview showing the first element

Asked

Viewed 81 times

1

I made this html preview, it works very well for my purpose but 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 would like to understand what is going wrong.
Put <div></div> the opening tag appears: <div>, but only the first, the rest of the code does not appear
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>
<textarea id="copy" onInput="showPreview();"><div><img src='https://i.imgur.com/FfInIT9.jpg' width='100'/></div>
</textarea>
<br>
<div id="preview"/>

  • How so but the first element is appearing as text?

  • if you put <div></div> the opening tag appears: <div>

  • You don’t want any tag openings to appear?

  • yes, run the snippet and paste: <div><div><div> you will see that only the first <div> appears

2 answers

0

This is why you’re giving replace, but inserting the character again, so it shows the first one. You have to leave it empty, so that the characters do not appear:

The regular expression: /</g inside the replace serves so that every time the text is found < and > are replaced by something, which in this case 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>
<textarea id="copy" onInput="showPreview();">
</textarea>
<br>
<div id="preview"></div>

0


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

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

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

I hope I’ve helped.

  • I had tried so before, but I couldn’t think I was doing anything wrong, so I opted for replace helped a lot thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.