0

I have a Ordered list with a class named as comments.
So i am pushing values from my text area into a variable named my_html_syntax.

The code works fine the only problem is how do I stop html syntax from rendering for example when i enter html syntax for a buttton it renders the button into my ul.

how do i escape my javascript variable my_html_syntax

SOLVED -thanks to justinas this is how i used it .

<html>

<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-    2.1.1.min.js"></script>

<script>

$(document).ready(function() {

$('button').click(function() {
function htmlEntities(str) {
 return String(str).replace(/&/g,'&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

var my_html_syntax= $('#textarea').val(); 

$('ul').append('<li>' + htmlEntities(my_html_syntax) +'</li>');


   });
      });

 </script>

</head>
<body>
<textarea id="textarea" class="textarea" rows="4" cols="50"> </textarea>

<button class="doit" id="doit" type="button" value="submit">   submit</button>

<ul class="comments" id="comments">  asd </ul>

</body>

  </html>
user3548161
  • 119
  • 5
  • 18

2 Answers2

1

You can escape HTML entities to be shown:

function htmlEntities(str) {
  return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

$(document).ready(function() {
  $('ul').append("<li>" + htmlEntities("<a href='example.com'>LINK</a>") + "</li>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>

Source

Justinas
  • 41,402
  • 5
  • 66
  • 96
0

Bad ways.

You have to use .text().

$("<li></li>")
    .text(my_html_syntax)
    .appendTo($('.comments'));

Or with .append() :

$('.comments').append($("<li></li>").text(my_html_syntax));
user2226755
  • 12,494
  • 5
  • 50
  • 73