1

I was wondering if there is a way I could apply htmlentities() to var x so that if I put <p>hello</p> into the text area and press the button it would display <p>hello</p> instead of hello using the below code.

Thanks in advance

function myFunction1() {
  var x = document.getElementById("myText1").value;
  document.getElementById("demo1").innerHTML = x;
}
<textarea name="myText" id="myText1" type="text"></textarea>
<button onclick="myFunction1()">thing</button>
<p><span id="demo1"></span></p>

2 Answers 2

1

You need to use <xmp> tag

<xmp>
  <p>hello</p>
</xmp>

function myFunction1() {
  var x = document.getElementById("myText1").value;
  document.getElementById("demo1").innerHTML = x;
}
<textarea name="myText" id="myText1" type="text"></textarea>
<button onclick="myFunction1()">Show</button>
<p><xmp id="demo1"></xmp></p>

Sign up to request clarification or add additional context in comments.

1 Comment

<xmp> tag is deprecated so might not work in all browsers. <pre> or <code> tag is preferred.
0

Generally this is done by replacing the < symbol with the "less than" HTML encoding (&lt;), and > with "greater than" (&gt;).

For instance, you should use basic string methods to replace something like

"<p>hello</p>"

with

"&lt;p&gt;hello&lt;/p&gt;"

(Otherwise, adding it to an element's innerHTML will read it as HTML, including the tags.)

I should point out that you can also try just wrapping everything in the <pre> tag, but I've had varying results with it. I think the method above is a safer bet.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.