302

How can I show HTML snippets on a webpage without needing to replace each < with &lt; and > with &gt;?

In other words, is there a tag for don't render HTML until you hit the closing tag?

0

31 Answers 31

220

The tried and true method for HTML:

  1. Replace the & character with &amp;
  2. Replace the < character with &lt;
  3. Replace the > character with &gt;
  4. Optionally surround your HTML sample with <pre> and/or <code> tags.
6
  • 19
    Tip: To speed up the HTML code replacement you can use Notepad++ with extension 'TextFX'. Mark the text, go to menu >TextFX >TextFX Convert >Encode HTML (&<>") → Done.
    – Avatar
    Commented Jan 13, 2013 at 18:07
  • 2
    Is there any existing JavaScript library that can do this, by any chance? Commented Apr 12, 2013 at 22:42
  • 14
    This does not answer the question, which said “without needing to replace...”. Besides, replacing “>” is unnecessary. Commented Apr 24, 2014 at 11:19
  • 3
    And the order is important too. Make sure you handle the & first and < afterwards. Commented Jun 18, 2015 at 5:34
  • 3
    @AndersonGreen Here's the library: export const escapeHtml = str => str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'). Maybe someone should create an NPM package for it, like left-pad? 😆 Commented Sep 10, 2020 at 20:01
188

sample 1:

<pre>
  This text has
  been formatted using
  the HTML pre tag. The brower should
  display all white space
  as it was entered.
</pre>

sample 2:

<pre>
  <code>
    My pre-formatted code
    here.
  </code>
</pre>

sample 3: (If you are actually "quoting" a block of code, then the markup would be)

<blockquote>
  <pre>
    <code>
        My pre-formatted "quoted" code here.
    </code>
  </pre>
</blockquote>
5
  • 8
    The elements used in the answer do not address the question at all: they do not affect the interpretation of “<” starting a tag. Commented Apr 24, 2014 at 11:17
  • 14
    developer.mozilla.org/en-US/docs/Web/HTML/Element/xmp says, "Do not use this element. It has been deprecated since HTML3.2 and was not implemented in a consistent way. It was completely removed from the language in HTML5."
    – Nick Rice
    Commented Aug 1, 2018 at 8:40
  • I used the posted CSS, thanks, it fixed a lot of design issues Commented Aug 31, 2020 at 9:41
  • It does not works, the string List<int> will only show List when you do this
    – GuidoG
    Commented Dec 15, 2022 at 9:03
  • @NickRice but I can't stop, and I will continue to use <xmp> and <plaintext>, because html gives no other way to show &amp; text instead of a symbol in the 21st century, Carl!
    – kirogasa
    Commented Aug 18, 2023 at 17:43
156

is there a tag for don't render HTML until you hit the closing tag?

No, there is not. In HTML proper, there’s no way short of escaping some characters:

  • & as &amp;
  • < as &lt;

(Incidentally, there is no need to escape > but people often do it for reasons of symmetry.)

And of course you should surround the resulting, escaped HTML code within <pre><code>…</code></pre> to (a) preserve whitespace and line breaks, and (b) mark it up as a code element.

All other solutions, such as wrapping your code into a <textarea> or the (deprecated) <xmp> element, will break.1

XHTML that is declared to the browser as XML (via the HTTP Content-Type header! — merely setting a DOCTYPE is not enough) could alternatively use a CDATA section:

<![CDATA[Your <code> here]]>

But this only works in XML, not in HTML, and even this isn’t a foolproof solution, since the code mustn’t contain the closing delimiter ]]>. So even in XML the simplest, most robust solution is via escaping.


1 Case in point:

textarea {border: none; width: 100%;}
<textarea readonly="readonly">
  <p>Computer <textarea>says</textarea> <span>no.</span>
</textarea>

<xmp>
  Computer <xmp>says</xmp> <span>no.</span>
</xmp>

14
  • 2
    Nice. So that's part of the HTML standard? Or is it deeper, like part of the xml-standard?
    – aioobe
    Commented May 12, 2010 at 15:50
  • 7
    In HTML, this will render ` here]]>`
    – Dolph
    Commented May 12, 2010 at 16:03
  • 3
    Yes, this is a good answer, but don't forget to replace > with &gt;
    – Alan
    Commented Jul 28, 2016 at 13:13
  • 2
    @Alan I’d do this too, but it’s not actually necessary: only < and & need to be replaced, unescaped > is valid inside HTML. Commented Jul 28, 2016 at 13:25
  • 3
    @SamWatkins But your solution isn’t any easier than mine. You’ve just changed what needs to be escaped, and your solution is hacky, as you admit. There is literally no advantage over doing it properly. This is a solved problem with a correct solution. No need for hacks, unless your whole setup is hacky. Commented Jun 3, 2020 at 8:28
70

Kind of a naive method to display code will be including it in a textarea and add disabled attribute so its not editable.

<textarea disabled> code </textarea>

Hope that help someone looking for an easy way to get stuff done.


But warning, this won't escape the tags for you, as you can see here (the following obviously does not work):

<textarea disabled>

This is the code to create a textarea:
<textarea></textarea>

</textarea>

5
  • 12
    Readonly may be a better attribute than disabled so as you can highlight the text within it. Also possibly adding a style that strips it of any features that makes it look like an input element, although that is secondary.
    – Tarquin
    Commented Apr 14, 2016 at 7:04
  • 2
    Awesome solution. Thanks Commented Aug 15, 2017 at 16:04
  • 3
    Ampersands will still be interpreted. eg &nbsp; will be rendered as an actual non-breaking space. But good answer nevertheless that is ideal for something I want to do.
    – Nick Rice
    Commented Aug 1, 2018 at 10:01
  • 1
    I've tried many ways, and this is the only way that works for me. Thanks a lot. Commented Jun 21, 2019 at 21:57
  • 1
    Great! works in Chrome, Edge and Firefox on Windows 10.
    – MT1
    Commented Jul 9, 2020 at 14:46
32

Deprecated, but works in FF3 and IE8.

<xmp>
   <b>bold</b><ul><li>list item</li></ul>
</xmp>

Recommended:

<pre><code>
    code here, escape it yourself.
</code></pre>
0
15

i used <xmp> just like this : http://jsfiddle.net/barnameha/hF985/1/

2
  • 2
    it has been deprecated
    – EdgeDev
    Commented Mar 21, 2019 at 21:38
  • @EdgeDev it has no alternative, so whatever about deprecated.
    – kirogasa
    Commented Aug 18, 2023 at 17:46
13

The deprecated <xmp> tag essentially does that but is no longer part of the XHTML spec. It should still work though in all current browsers.

Here's another idea, a hack/parlor trick, you could put the code in a textarea like so:

<textarea disabled="true" style="border: none;background-color:white;">
    <p>test</p>
</textarea>

Putting angle brackets and code like this inside a text area is invalid HTML and will cause undefined behavior in different browsers. In Internet Explorer the HTML is interpreted, whereas Mozilla, Chrome and Safari leave it uninterpreted.

If you want it to be non-editable and look different then you could easily style it using CSS. The only issue would be that browsers will add that little drag handle in the bottom-right corner to resize the box. Or alternatively, try using an input tag instead.

The right way to inject code into your textarea is to use server side language like this PHP for example:

<textarea disabled="true" style="border: none;background-color:white;">
    <?php echo '<p>test</p>'; ?>
</textarea>

Then it bypasses the html interpreter and puts uninterpreted text into the textarea consistently across all browsers.

Other than that, the only way is really to escape the code yourself if static HTML or using server-side methods such as .NET's HtmlEncode() if using such technology.

4
  • 1
    this is a horrible idea. What if it was dynamic html being displayed, and someone did the following. <?php echo '</textarea><script>alert(\'hello world\');</script><textarea>'; />. Therefore your code is vulnerable to xss. Commented Aug 18, 2014 at 23:01
  • PHP is server-side, so it does not change the result seen by the browser. It especially does not bypass the HTML interpreter. Commented Jan 7, 2017 at 14:54
  • I like the formatting of the textarea to make it not look like an input box. I also add width 100% to reduce wrapping: <textarea disabled="true" style="border: none;background-color:white; width:100%">
    – Dan King
    Commented Jan 12, 2018 at 22:40
  • @GaryDrocella if you insert <script> tags into tetarea, they are converted to &lt; and &gt; automatically, so no script is ever executed Commented Jan 23, 2020 at 3:42
10

If your goal is to show a chunk of code that you're executing elsewhere on the same page, you can use textContent (it's pure-js and well supported: http://caniuse.com/#feat=textcontent)

<div id="myCode">
    <p>
        hello world
    </p>
</div>

<div id="loadHere"></div>


document.getElementById("myCode").textContent = document.getElementById("loadHere").innerHTML;

To get multi-line formatting in the result, you need to set css style "white-space: pre;" on the target div, and write the lines individually using "\r\n" at the end of each.

Here's a demo: https://jsfiddle.net/wphps3od/

This method has an advantage over using textarea: Code wont be reformatted as it would in a textarea. (Things like &nbsp; are removed entirely in a textarea)

1
  • That's quite a nice approach, to use JavaScript and the DOM API to do the escaping for us. We could use it along with a <template> or something that is not normally rendered. Commented Jun 7, 2020 at 9:15
8

I assume:

  • you want to write 100% valid HTML5
  • you want to place the code snippet (almost) literal in the HTML
    • especially < should not need escaping

All your options are in this tree:

  • with HTML syntax
    • there are five kinds of elements
    • those called "normal elements" (like <p>)
      • can't have a literal <
      • it would be considered the start of the next tag or comment
    • void elements
      • they have no content
      • you could put your HTML in a data attribute (but this is true for all elements)
      • that would need JavaScript to move the data elsewhere
      • in double-quoted attributes, " and &thing; need escaping: &quot; and &amp;thing; respectively
    • raw text elements
      • <script> and <style> only
      • they are never rendered visible
      • but embedding your text in Javascript might be feasable
      • Javascript allows for multi-line strings with backticks
      • it could then be inserted dynamically
      • a literal </script is not allowed anywhere in <script>
    • escapable raw text elements
      • <textarea> and <title> only
      • <textarea> is a good candidate to wrap code in
      • it is totally legal to write </html> in there
      • not legal is the substring </textarea for obvious reasons
        • escape this special case with &lt;/textarea or similar
      • &thing; needs escaping: &amp;thing;
    • foreign elements
      • elements from MathML and SVG namespaces
      • at least SVG allows embedding of HTML again...
      • and CDATA is allowed there, so it seems to have potential
  • with XML syntax

 

Note: > never needs escaping. Not even in normal elements.

2
  • 1
    I like the comprehensive approach of your answer. A few corrections: <script> and <style> can be rendered visible, just put them inside the <body> with style="display: block; white-space: pre;" and type="text/html" or something if you don't want it to be executed as JavaScript. It's quite a nice trick I think, good for literate programming and teaching. Also <xmp> is still implemented in major browsers, although it is deprecated. Commented Jun 7, 2020 at 9:11
  • Interesting. @SamWatkins <xmp> is not valid HTML5, but your other trick looks proper! Commented Jun 7, 2020 at 14:54
7

In HTML? No.

In XML/XHTML? You could use a CDATA block.

6
<textarea ><?php echo htmlentities($page_html); ?></textarea>

works fine for me..

"keeping in mind Alexander's suggestion, here is why I think this is a good approach"

if we just try plain <textarea> it may not always work since there may be closing textarea tags which may wrongly close the parent tag and display rest of the HTML source on the parent document, which would look awkward.

using htmlentities converts all applicable characters such as < > to HTML entities which eliminates any possibility of leaks.

There maybe benefits or shortcomings to this approach or a better way of achieving the same results, if so please comment as I would love to learn from them :)

3
  • 2
    While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.
    – Alexander
    Commented Jan 10, 2018 at 3:45
  • 1
    If you're using htmlentities() like that, <textarea> becomes redundant. Just put it in a div or something. The OP didn't suggest they were using PHP at all though.
    – Nick Rice
    Commented Aug 1, 2018 at 10:10
  • @Nick yeah well, in my opinion textarea serves as a natural container as it will automatically add scrollbars and stuff which otherwise need styling if we put it in div of something..
    – Anupam
    Commented Aug 22, 2019 at 8:24
5

It's vey simple .... Use this xmp code

    <xmp id="container">

&lt;xmp &gt;

    <p>a paragraph</p>

    &lt;/xmp &gt;

</xmp>
5

This is a simple trick and I have tried it in Safari and Firefox

<code>
    <span><</span>meta property="og:title" content="A very fine cuisine" /><br>
    <span><</span>meta property="og:image" content="http://www.example.com/image.png" />
</code>

It will show like this:

enter image description here

You can see it live Here

4

You could try:

Hello! Here is some code:

<xmp>
<div id="hello">

</div>
</xmp>

1
  • Please add some explanation to your code such that others can learn from it
    – Nico Haase
    Commented Sep 26, 2022 at 6:21
4

This is a bit of a hack, but we can use something like:

body script {
    display: block;
    font-family: monospace;
    white-space: pre;
}
<script type="text/html">
<h1>Hello World</h1>

<ul>
    <li>Enjoy this dodgy hack,
    <li>or don't!
</ul>
</script>

With that CSS, the browser will display scripts inside the body. It won’t attempt to execute this script, as it has an unknown type text/html. It’s not necessary to escape special characters inside a <script>, unless you want to include a closing </script> tag.

I’m using something like this to display executable JavaScript in the body of the page, for a sort of "literate progamming".

There’s some more info in this question When should tags be visible and why can they?.

3
function escapeHTML(string)
    { 
        var pre = document.createElement('pre');
        var text = document.createTextNode(string);
        pre.appendChild(text);
        return pre.innerHTML;
}//end escapeHTML

it will return the escaped Html

2

There are a few ways to escape everything in HTML, none of them nice.

Or you could put in an iframe that loads a plain old text file.

2

Ultimately the best (though annoying) answer is "escape the text".

There are however a lot of text editors -- or even stand-alone mini utilities -- that can do this automatically. So you never should have to escape it manually if you don't want to (Unless it's a mix of escaped and un-escaped code...)

Quick Google search shows me this one, for example: http://malektips.com/zzee-text-utility-html-escape-regular-expression.html

1
  • How woul "escape the text" work in details? Also, why should one add a text editor for this? Finally, the link you've shared does not provide any information about how to show HTML code
    – Nico Haase
    Commented Sep 26, 2022 at 6:23
2

This is by far the best method for most situations:

<pre><code>
    code here, escape it yourself.
</code></pre>

I would have up voted the first person who suggested it but I don't have reputation. I felt compelled to say something though for the sake of people trying to find answers on the Internet.

2

You could use a server side language like PHP to insert raw text:

<?php
  $str = <<<EOD
  <html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="description" content="Minimal HTML5">
    <meta name="keywords" content="HTML5,Minimal">
    <title>This is the title</title>
    <link rel='stylesheet.css' href='style.css'>
  </head>
  <body>
  </body>
  </html>
  EOD;
?>

then dump out the value of $str htmlencoded:

<div style="white-space: pre">
  <?php echo htmlentities($str); ?>
</div>
1

Actually there is a way to do this. It has limitation (one), but is 100% standard, not deprecated (like xmp), and works.

And it's trivial. Here it is:

<div id="mydoc-src" style="display: none;">
LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo
<!--
YOUR CODE HERE.
    <script src="WidgetsLib/all.js"></script>
    ^^ This is a text, no side effects trying to load it.
-->
LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo
</div>

Please let me explain. First of all, ordinary HTML comment does the job, to prevent whole block be interpreted. You can easily add in it any tags, all of them will be ignored. Ignored from interpretation, but still available via innerHTML! So what is left, is to get the contents, and filter the preceding and trailing comment tokens.

Except (remember - the limitation) you can't put there HTML comments inside, since (at least in my Chrome) nesting of them is not supported, and very first '-->' will end the show.

Well, it is a nasty little limitation, but in certain cases it's not a problem at all, if your text is free of HTML comments. And, it's easier to escape one construct, then a whole bunch of them.

Now, what is that weird LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo string? It's a random string, like a hash, unlikely to be used in the block, and used for? Here's the context, why I have used it. In my case, I took the contents of one DIV, then processed it with Showdown markdown, and then the output assigned into another div. The idea was, to write markdown inline in the HTML file, and just open in a browser and it would transform on the load on-the-fly. So, in my case, <!-- became transformed to <p><!--</p>, the comment properly escaped. It worked, but polluted the screen. So, to easily remove it with regex, the random string was used. Here's the code:

    var converter = new showdown.Converter();
    converter.setOption('simplifiedAutoLink', true);
    converter.setOption('tables', true);
    converter.setOption('tasklists', true);
    var src = document.getElementById("mydoc-src");
    var res = document.getElementById("mydoc-res");
    res.innerHTML = converter.makeHtml(src.innerHTML)
            .replace(/<p>.{0,10}LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo.{0,10}<\/p>/g, "");
    src.innerHTML = '';

And it works.

If somebody is interested, this article is written using this technique. Feel free to download, and look inside the HTML file.

It depends what you are using it for. Is it user input? Then use <textarea>, and escape everything. In my case, and probably it's your case too, I simply used comments, and it does the job.

If you don't use markdown, and just want to get it as is from a tag, then it's even simpler:

<div id="mydoc-src" style="display: none;">
<!--
YOUR CODE HERE.
    <script src="WidgetsLib/all.js"></script>
    ^^ This is a text, no side effects trying to load it.
-->
</div>

and JavaScript code to get it:

    var src = document.getElementById("mydoc-src");
    var YOUR_CODE = src.innerHTML.replace(/(<!--|-->)/g, "");
1

Convert your HTML here https://wtools.io/convert-html-encoder-decoder

Paste the converted code inside pre

<pre>
 <code>Converted code</code>
</pre>
0

I used this a long time ago and it did the trick for me, I hope it helps you too.

var preTag = document.querySelectorAll('pre');
console.log(preTag.innerHTML);
for (var i = 0; i < preTag.length; i++) {
  var pattern = preTag[i].innerHTML;
  pattern = pattern.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  console.log(pattern);
  preTag[i].innerHTML = pattern;
}
<pre>
  <p>example</p>
  <span>more text</span>
</pre>

1
  • This is awesome. It was a solid solution for my situation! (rendering a doc from Firestore that also have a code snip on it) thanks... Commented Aug 4 at 16:25
0

If you are looking for a solution that works with frameworks.

const code = `
 <div>
  this will work in react
 <div>
`
<pre>
  <code>{code}</code>
</pre>

And you can give it a nice look with css:

pre code {
    background-color: #eee;
    border: 1px solid #999;
    display: block;
    padding: 20px;
}
0

JavaScript string literals can be used to write the HTML across multiple lines. Obviously, JavaScript, ECMA6 in particular, is required for this solution.

.createTextNode paired with CSS white-space: pre-wrap; does the trick.

.innerText alone also works. Run code snippet below.

let codeBlock = `
<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>My Page</title>
 </head>
 <body>
  <h1>Welcome to my page</h1>
  <p>I like cars and lorries and have a big Jeep!</p>
  <h2>Where I live</h2>
  <p>I live in a small hut on a mountain!</p>
 </body>
</html>
`
const codeElement = document.querySelector("#a");
let textNode = document.createTextNode(codeBlock);
codeElement.appendChild(textNode);

const divElement = document.querySelector("#b");
divElement.innerText = codeBlock;
#a {
  white-space: pre-wrap;
}
<div id=a>

</div>

<div id=b>

</div>

-1

This is how I did it:

$str = file_get_contents("my-code-file.php");
echo "<textarea disabled='true' style='border: none;background-color:white;'>";
echo $str;
echo "</textarea>";
3
  • this code is vulnerable to xss. anyone can set $str="</textarea><textarea>" Commented Aug 18, 2014 at 23:05
  • Hiya, this may well solve the problem... but it'd be good if you could provide a little explanation about how and why it works :) Don't forget - there are heaps of newbies on Stack overflow, and they could learn a thing or two from your expertise - what's obvious to you might not be so to them.
    – Taryn East
    Commented Aug 18, 2014 at 23:18
  • Please add some explanation to your answer such that others can learn from it
    – Nico Haase
    Commented Sep 26, 2022 at 6:22
-1

It may not work in every situation, but placing code snippets inside of a textarea will display them as code.

You can style the textarea with CSS if you don't want it to look like an actual textarea.

0
-1
 //To show xml tags in table columns you will have to encode the tags first

function htmlEncode(value) {
    //create a in-memory div, set it's inner text(which jQuery automatically encodes)
    //then grab the encoded contents back out.  The div never exists on the page.
    return $('<div/>').text(value).html();
}

html = htmlEncode(html)
-1

A combination of a couple answers that work together here:

function c(s) {
    return s.split("&lt;").join("<").split("&gt;").join(">").split("&amp;").join("&")
}

displayMe.innerHTML = ok.innerHTML;
console.log(
  c(ok.innerHTML)
)
<textarea style="display:none" id="ok">
<script>
console.log("hello", 5&9);
</script>
</textarea>
<div id="displayMe">

</div>

-1

You can separate the tags by changing them to spans.

Like this:

<span><</span> <!-- opening bracket of h1 here -->
<span>h1></span> <!-- opening tag of h1 completed here -->
<span>hello</span> <!-- text to print -->
<span><</span> <!-- closing h1 tag's bracket here -->
<span>/h1></span> <!-- closing h1 tag ends here -->

And also, you can just only add the <(opening angle bracket) to the spans

<span><</span> <!-- opening bracket of h1 here -->
h1> <!-- opening tag of h1 completed here -->
hello <!-- text to print -->
<span><</span> <!-- closing h1 tag's bracket here -->
/h1><!-- closing h1 tag ends here -->

2
  • How is this in any way better than replacing opening < with &lt;? Commented Jul 31, 2021 at 14:16
  • Where does your code print markup in any way?
    – Nico Haase
    Commented Sep 26, 2022 at 6:20

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