Reputation: 576
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>
Upvotes: 3
Views: 1410
Reputation: 3441
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>
Upvotes: 0
Reputation: 613
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>");
Upvotes: 0
Reputation: 22490
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>
Upvotes: 3
Reputation: 1679
Maybe you could do something like:
$("#feed").append("<b>Hello World!</b>");
Or:
$("#feed").append("<xmp><b>Hello World!</b></xmp>");
But note that the xmp
tag is deprecated.
Upvotes: 0
Reputation: 36609
Escape HTML
Characters [Ref]
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
$("#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>
Upvotes: 2
Reputation: 821
Have you checked the
<!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>
Upvotes: 0