TheRogerLAB Codes

Display code in HTML

  July, 2021

Introduction

There are some characters reserved in HTML. For example if we want to display a code snippet like this <div>Hello world</div> and only type this code in HTML, we will get this result "Hello world" the rest will "disappear" because the page will consider the less than (<) or greater than (>) signs as a HTML tag. Here is where we need HTML entities, that are used to display those reserved characters in HTML.

Hence we are going to replace:

So this code:

<div>
  <div>
    Hello world
  </div>
</div>

Will look like this:

&lt;div&gt;<br>
&nbsp;&nbsp;&lt;div&gt;<br>
&nbsp;&nbsp;&nbsp;&nbsp;Hello&nbsp;world<br>
&nbsp;&nbsp;&lt;/div&gt;<br>
&lt;/div&gt;

With this "format" you can type or paste the code in your HTML and it will look perfect.

Can I use a textarea?

Probably you are thinking: "But I can achieve this by using a textarea tag" and you are right. A simple way to do this is wrapping the code inside a textarea tag and most of the time it will work. And it is ok but only if you want to display the code without syntax highlighting.

Syntax highlighting

On the other hand, I you want to use syntax highlighting, you will prefer to use HTML entities. This is because you can easily put some color style to your code snippet. For example wrapping your key words into a span tag and giving it some color.

Hence, this code:

<span style="color:red">
&lt;div&gt;<br>
</span>
&nbsp;&nbsp;Hello world<br>
<span style="color:red">
&lt;/div&gt;<br>
</span>

Will be displayed as:

<div>
  Hello world
</div>

Doing it all manually?

So far so good, but when your code snippet gets more complex then it will be more difficult to do this manually. That is the reason for what we have developed a free online tool to "format" your HTML, CSS or JS code snippet. Just type or paste your code and get it formatted or highlighted ready to use in your HTML. Beautiful code like these.

HTML snippet:

<div class="myClass" onclick="myFunction()">
  Hello world
</div>

CSS snippet:

.myClass{
  font-size:18px;
  color:red;
  text-align:center;
}

JS snippet:

function myFunction(){
  var el= document.querySelector(".myClass");
  for(var i=0; i<10; i++){
    el.innrHTML = "This is new content";
    var msg = "Content changed" + (i + 1);
    console.log(msg);
  }  
}
TRY ONLINE TOOL RATE THIS ARTICLE
4.8
6
TheRogerLAB Codes
Powered by TheRogerLAB Sandbox

info@therogerlab.com