Skip to main content | Turn off styling Default page style

Question & Answer index

How do you display HTML code in your pages?

Have you ever tried to display HTML on your webpage as HTML? Typically, this requires that you right up perfectly good HTML then, manually, go through it converting all of the < into &gt; and > into &gt;. This makes viewing the source of the page difficult to read and, if you need to edit the HTML later, a real pain!

Here is my approach, using a combination of jQuery and regular JavaScript, which I think you will find relatively easy to use.

  1. Create the HTML that you want to display and save it as a separate file. Like this.
  2. Create the location on your page where you want the HTML to display. Here is an example using a span, but you can use whatever type of element you want (p, div, td, etc.), so long as it supports the id attribute:
  3. Add this function to your javascript Library:
  4. Add a call to loadCode inside your $(document).ready. Here are the 3 calls used to populate the three code blocks displayed on this page:

That's it!

The fun part is deciding on how you are going to format your code so that it fits with the design of your site!