robert devverlo
robert devverlo

Reputation: 129

How to show JavaScript code on a web page?

How to show the following Javascript code, but not run it?

<script>alert("test");</script>

I tried to show this code on my page, but when user loads the page it alerts "test".

How can I show the code but not run it on page load?

Upvotes: 2

Views: 3555

Answers (3)

Keval Bhatt
Keval Bhatt

Reputation: 6322

<pre><code>&lt;script&gt;alert('test')&lt;/script&gt;
 </code></pre>


OR

Using Jquery you can simply add text on particular selector using .text()

Jquery example:

$(document).ready(function () {
        $('.showText').text("<script>alert('text')<"+"/script>");
           });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<span class="showText"></span>

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 205987

<!-- Sadly (totally)... this is obsolete :( -->
<xmp>
<script>alert("test");</script>
</xmp>

http://www.w3.org/TR/REC-html32#xmp
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/plaintext
https://code.google.com/p/doctype-mirror/wiki/PlaintextElement
http://www.blooberry.com/indexdot/html/tagpages/x/xmp.htm
http://www.blooberry.com/indexdot/html/tagpages/p/plaintext.htm

;) Great stuff but sadly you're on the browser's mercy since <plaintext> and <xmp> are obsolete,
so escaping the < and > characters with &lt; and &gt; (or with hex &#60;, &#62;)
is a far better idea.

&lt;script&gt;alert("test");&lt;/script&gt;

You can wrap the above for semantic reasons in tags like <pre> or <code> although it's not needed to achieve the desired.
So the point is that we're over and over suggested to use <pre>, yet we still miss a proper and valid tag to literalize and represent <, &, > without escaping.

Upvotes: -1

Tamil Selvan C
Tamil Selvan C

Reputation: 20199

Use &lt; for < and &gt; for >

<code>
    &lt;script&gt;alert("test");&lt;/script&gt;
</code>

Upvotes: 2

Related Questions