3

I want to add an HTML to a div but render it as text, not as actual HTML. I currently am doing this:

HTML

<div id="feed"></div>

Javascript/JQuery

$("#feed").append("<b>Hello World!</b>");

And it renders the following:

Hello World

But I want regular text to be rendered, like this

<b>Hello World!</b>
Adam Lee
  • 436
  • 1
  • 14
  • 49

6 Answers6

3

use text() instead of append() like this $("#feed").text("<b>Hello World!</b>");

If you append with more text use like this

$("#feed").text($("#feed").text()+"<b>Hello World!</b>");

$("#feed").text("<b>Hello World!</b>");

//$("#feed").text($("#feed").text()+"<b>Hello World!</b>"); for more append text use like this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="feed"></div>
prasanth
  • 22,145
  • 4
  • 29
  • 53
2

Escape HTML Characters [Ref]

function escapeHtml(unsafe) {
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

$("#feed").append(escapeHtml("<b>Hello World!</b>"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="feed"></div>
Community
  • 1
  • 1
Rayon
  • 36,219
  • 4
  • 49
  • 76
0

Have you checked the

http://api.jquery.com/html/

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>html demo</title>
  <style>
  p {
    margin: 8px;
    font-size: 20px;
    color: blue;
    cursor: pointer;
  }
  b {
    text-decoration: underline;
  }
  button {
    cursor: pointer;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>
  <b>Click</b> to change the <span id="tag">html</span>
</p>
<p>
  to a <span id="text">text</span> node.
</p>
<p>
  This <button name="nada">button</button> does nothing.
</p>

<script>
$( "p" ).click(function() {
  var htmlString = $( this ).html();
  $( this ).text( htmlString );
});
</script>

</body>
</html>
Nair Athul
  • 823
  • 9
  • 21
0

Maybe you could do something like:

$("#feed").append("&lt;b>Hello World!&lt;/b>");

Or:

$("#feed").append("<xmp><b>Hello World!</b></xmp>");

But note that the xmp tag is deprecated.

ESR
  • 1,669
  • 1
  • 18
  • 22
0

Please try it.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

       $("#feed").text("<b>Hello World!</b>");
});
</script>
</head>
<body>

<div id="feed"></div>

</body>
</html>
Pang
  • 9,564
  • 146
  • 81
  • 122
Md.Jewel Mia
  • 3,345
  • 3
  • 19
  • 24
0

For that you need to use ".text", which will simply append the text but will not render the html tags.

$("#feed").text("<b>Hello World!</b>");

WorkingFiddleLink

Akshay Chawla
  • 613
  • 1
  • 8
  • 16