Cannot display: <h1>abc</h1> on screen

Hi everyone,
I’d like to show this on my screen: " <h1>abc</h1> " I dont want the HTML header plus the code as text.
I tried this:

var i = 1;
    document.write("<h" + i + ">" + "abc" + "</h" + i + ">" + "\"<"  );

I only get: “ABC” and at the line below: "<
when I add "h1> It vanishes and all I can see is the ABC.
How can I show in JS the text: <h1>abc</h1> ?

You need to replace < and > with the hex code replacements (so it doesn’t get parsed as HTML).

var i = 1;
document.write("&lt;h" + i + "&gt;" + "abc" + "&lt;/h" + i + "&gt;");

&lt; is for < (less than)
&gt; is for > (greater than)


Thanks a lot Ryan !
Your solution worked as I expected because you never fail to provide the correct solution :grinning:
I thought JS had its own approach to special characters…

1 Like

Glad I could be of help :slight_smile: .

That command is effectively dead as it can’t run at the time regular JavaScript runs after the page loads or it overwrites the page completely.

You could use innerHTML instead and put an id in the page where you want the code inserted - or even better would be to use createElement, createTextNode and appendChild which are the JavaScript commands for properly adding HTML into the page.

Also you should put the JavaScript in a separate file.

There is no need to encode < and > in JavaScript and if you use the proper commands there will be no reason to even use them.

1 Like

Thanks fellgall,
I use external js files if I want to call a function. This time I wanted to show text when the page loads, how do I do that with an external file?

Felgall, in this case the complaint was the browser was interpreting the HTML and all they saw was the heading text. However, the OP wanted to see the brackets and everything.

So, similar to when we want to show code in a <pre> tag.

Here’s an example of how to code it properly to output HTML as text in the page from JavaScript

in the HTML

<div id="here"></div>

In the external JavaScript page attached to the bottom of the page:

var i = 1;
var h = document.getElementById('here');

Because that is using createTextNode it is outputting text and not HTML. To create an <h1> tag you’d use createElement('h1') instead and then appendChild the text to that. Completely different JavaScript commands for the two separate purposes.


I’ll give it a more insight consideration later and in the meanwhile i’ll just thank you.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.