1

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 &lt; and &gt;, but I want to avoid manual work.

2
  • This might be interesting for you
    – Aides
    Commented May 9, 2016 at 14:40
  • Do you still want the <p>-Tag to be a <p>-Tag (as in <p>&lt;p&gt; [...] &lt;/p&gt;</p>)?
    – Aides
    Commented May 9, 2016 at 14:54

3 Answers 3

4

try htmlEncode method as

function htmlEncode ( html )
{
    html = $.trim(html);
    return html.replace(/[&"'\<\>]/g, function(c) 
    {
          switch (c) 
          {
              case "&":
                return "&amp;";
              case "'":
                return "&#39;";
              case '"':
                return "&quot;";
              case "<":
                return "&lt;";
              default:
                return "&gt;";
          }
    });
};

Now encode the value as

$( "#example" ).html( htmlEncode ( $( "#example" ).html() ) );

DEMO

function htmlEncode ( html )
    {
    	html = $.trim(html);
    	return html.replace(/[&"'\<\>]/g, function(c) 
    	{
    		  switch (c) 
    		  {
    			  case "&":
    			    return "&amp;";
    			  case "'":
    			    return "&#39;";
    			  case '"':
    			    return "&quot;";
    			  case "<":
    			    return "&lt;";
     			  default:
    			    return "&gt;";
    		  }
    	});
    };

    $( "#example" ).html( htmlEncode ( $( "#example" ).html() ) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is how you should write paragraphs in HTML:</p>

<div id="example">

    <p>Foo</p>

</div>

0
0

This has been answered here: Is there a HTML/CSS way to display HTML tags without parsing?

<style>

script
{
    display: block;
}

</style>

<div id="example">
    Then within document body:
<script type="text/plain">
    <p>Foo</p>
</script>
</div>

JSfiddle: https://jsfiddle.net/9vkowqb3/

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);

Not the answer you're looking for? Browse other questions tagged or ask your own question.