Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using <pre> and <code> tags to display a javascript script

I'm experimenting with the < pre> and < code> tags in html 5 as I would like to include some code snippets on my website. I'm using the page below as a test page but it is not displaying anything. Any reason why?

    <body>
    <div style="color:#000000">
      <pre>
        <code>
          <script type="text/javascript">
            $('#inputField').hide();
          </script>
        </code>
      </pre>
    </div>
    </body>

It was my understanding that using these new tags would negate any code that they contain within however this does not appear to be the case.

Cheers,

J

like image 592
jezzipin Avatar asked Jul 26 '13 13:07

jezzipin


People also ask

How do you use tags in JavaScript?

You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.

How do I show a script in HTML?

To add a script, use the <script> tag. The HTML <script> tag is used for declaring a script (such as JavaScript) within your HTML document. Defines the character encoding that the script uses. Declares that the script will not generate any content.

What is the pre tag used for?

Definition and Usage. The <pre> tag defines preformatted text. Text in a <pre> element is displayed in a fixed-width font, and the text preserves both spaces and line breaks. The text will be displayed exactly as written in the HTML source code.

Where do I put script tag in JavaScript?

JavaScript in <head> or <body> You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.


2 Answers

It was my understanding that using these new tags would negate any code that they contain

They don't. They tell user agents to present the data as code. So it will have font changes, white space will be significant, it should be skipped over by translation software and so on.

Markup still takes effect (so you can add elements to style, or link the code to other places, and so on) so you still need to replace HTML special characters (<, &, etc) with their respective entities (&lt;, &amp;, etc).

like image 94
Quentin Avatar answered Nov 15 '22 17:11

Quentin


These tags are only for "decorational" purposes. Code within will still be executed. If you want it displayed you have to convert at least the <script> tag to html:

&lt;script type="text/javascript"&gt;

Then the JavaScript code inbetween will be shown.

You don't need both though, I would use <pre> (which is per default a block element), <code> is intended for inline use.

like image 22
Gerald Schneider Avatar answered Nov 15 '22 17:11

Gerald Schneider