Why are JS codes inside a pre or code block executed?

I am trying to show some JS codes on a page. I tried using

<pre > <code> <script type="text/javascript"> $(function(){ alert("Hello"); }); </script> </code> </pre> 

But if jQuery loads on the page, then I get a warning and the code does not appear. How can I show this JS without executing JS. I tried the SyntaxHighLighter plugin and it highlighted the code, but still I get a warning.

What is the best way to show this JS code to users without executing them.

+7
source share
2 answers

Because neither <pre> nor <code> means "Don't treat this as markup."

<pre> means "Play spaces here"

<code> means "Imagine this (i.e. use a suitable font, etc.) in such a way that it informs the reader that it is sample code."

If you want to use characters that have special meaning in HTML (for example, < ), you still have to use objects to represent them.

  • &lt; for <
  • &gt; for >
  • &amp; for &

You do not need to worry about ' or " since you are not inside the attribute value.

+19
source

Using <script> tags means it is javascript to execute.

Remove the <script> tags:

 <pre> <code> $(function(){ alert("Hello"); }); </code> </pre> 

Alternatively, encode the < and > tags in &lt; and &gt; so the <script> tags are displayed as text and are not interpreted as script tags:

 <pre> <code> &lt;script type="text/javascript"&gt; $(function(){ alert("Hello"); }); &lt;/script&gt; </code> </pre> 
+5
source

All Articles