Search code examples
javascripthtmlhtml-escape-characters

How do I escape html tags in javascript?


So here is my simplified code :

TestHTML.html

<html>
<script src = "TestJs.js"></script>
<body>
<a onclick="var content = 'one<br>two<br>three' ; showContent(content);">Click here</a>
</body>
</html>        

TestJs.js

function showContent(content){

var popup = open("", "PopUp", "width=300,height=200");
var pTag = popup.document.createElement("p");
pTag.innerHTML = content;
popup.document.body.appendChild(pTag);

};        

Here my requirement is whenever I click on a reference link on page (named Click here) a popup should open and display the content sent through onclick. The above code is working fine and I get popup result in the form

one
two 
three

but things go wrong when I try to put angled brackets as text like

<a onclick="var content = '<one><br>two<br>three' ; showContent(content);">Click here</a>

I got the result for above code in the form

two
three

i.e text in angled bracket is escaped.

I am aware of the fact that angled brackets are html entities and I need to escape them. I tried to send ASCII for <> i.e &lt; and &gt; through onclick like

<a onclick="var content = '&lt;one&gt;<br>&lt;two&gt;<br>&lt;three&gt;' ; showContent(content);">Click here</a>

but the text get converted to its original form when passed to javascript funtion and subsequently get skipped in popup(i.e. blank popup).

So my questions here are:

  1. How do I escape the html tag in javascript while creating html document?
  2. How ASCII text is converted back to normal text automatically when it is passed as argument to javascript function?

Solution

  • Look at what you have.

    1. The character <
    2. Which needs to be expressed (because it is assigned to innerHTML) as HTML so the < has to be written &lt;
    3. But that is embedded inside an HTML attribute, where it will be interpreted as HTML when the HTML parser constructs the attribute value in the DOM. & has special meaning in HTML, so the & must be represented as &amp;

    So &amp;lt;