Reputation: 129
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
Reputation: 6322
<pre><code><script>alert('test')</script>
</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
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 <
and >
(or with hex <
, >
)
is a far better idea.
<script>alert("test");</script>
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
Reputation: 20199
Use <
for <
and >
for >
<code>
<script>alert("test");</script>
</code>
Upvotes: 2