-4

I'm trying to print plain html from javascript and can't figured out how to do so. Example:

$('#elem').html('This is a normal string'); // --> This is a normal string

$('#elem').html('This <b>contains</b> html')
//Current-> This contains html   (contains is bold)
//Wanted-> This <b>contains</b> html

I want to do this because I'm working with comments written by users and don't want html tags to apply if they put some in their comments. But for other reasons I need to see the tags.

Thanks for your help!

Alexandre Fradette
  • 312
  • 1
  • 6
  • 14

3 Answers3

1

Use the jQuery .text() function, which automatically escapes HTML to text for you!

In this example it is:

$('#elem').text('This <b>contains</b> html')
AP.
  • 8,082
  • 2
  • 24
  • 33
1

The following should work:

$('#elem').text('This <b>contains</b> html');

Related Snippet:

$('#an-id').text('<b>I don\'t want this to be HTML</b>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="an-id">This is not HTML!</p>

Good luck!

Check the jQuery documentation for more information.

AryanJ-NYC
  • 2,529
  • 2
  • 20
  • 27
-1

you could use the jQuery .text() method.

$('#elem').text('This <b>contains</b> html');

example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#elem").text('This <b>contains</b> html');
    });
});
</script>
</head>
<body>

<button>Click ME!!</button>

<p id="elem">This is a paragraph.</p>
   
</body>
</html>
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126