For example, I have a test page like this:
index.html:
<p>This is how you should write paragraphs in HTML:</p> <div id="example"> <p>Foo</p> </div>If I open this page in the browser, I want to see both text and tags:
This is how you should write paragraphs in HTML: <p>Foo</p>How it may be automatically done with js?
Yes, I can manually replace < and > by < and >, but I want to avoid manual work.
asked May 9, 2016 at 14:28
2
try htmlEncode method as
function htmlEncode ( html ) { html = $.trim(html); return html.replace(/[&"'\<\>]/g, function(c) { switch (c) { case "&": return "&"; case "'": return "'"; case '"': return """; case "<": return "<"; default: return ">"; } }); };Now encode the value as
$( "#example" ).html( htmlEncode ( $( "#example" ).html() ) );DEMO
answered May 9, 2016 at 14:31
gurvinder372gurvinder372
65.2k9 gold badges69 silver badges90 bronze badges
0
Check the following jsfiddle HTML:
<p>This is how you should write paragraphs in HTML:</p> <div id="example"> </div>JS:
var text = document.createTextNode('<p>Stuff</p>'); document.getElementById('example').appendChild(text);answered May 9, 2016 at 14:37
Sagi LeviSagi Levi
3051 silver badge11 bronze badges
Basically, there are two methods for displaying HTML tags as plain text.
1. Using <plaintext> element: Plaintext element is deprecated which means this feature is no longer supported. Though some browsers might still support it, it is not recommended to use.
2. HTML entities: The second and only option available is using html entities. < ,> are reserved characters in HTML, In order to display this reserved characters you have to replace them with html entities. You can learn more about entities here. You can either use entity name or entity number initializing them with & and ending them with ;
Refer to below table for required html entities:
Sign | Description | Entity name | Entity number |
< | Less than(start of html element) | < | < |
> | Greater than(end of html element) | > | > |
“ | Double quotation | " | " |
& | Ampersand ( beginning of html entity) | & | & |
Example 1: In the first example, we are using html entity names to display body element and paragraph element on web page.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Plain text </title>
</head>
<body>
<pre>
Paragraph element: <p> </p>
Body element : < body > < /body >
</pre>
</body>
</html>
Output:
Output
Explanation: In above code, “<” and “>” is simply replaced by their respective html entities.<pre></pre> is html element which defines preformatted text.
Example 2: In below example, we are trying to display html entity name for “<” using entity name for “&” sign.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Plain text demo</title>
</head>
<body>
<pre>
< is entity name for <
</pre>
</body>
</html>
Output:
Output
Explanation: In above example, “&” is replaced with “&” and “<“ is replaced with “<”