1

I want to have a prompt box asking the user for their name. But I'm putting that directly into the page, and if I enter something HTML-y (<canvas> for example) then it places that element on the page. How can I make this into text, so instead of making a <canvas> element it writes <canvas> to the page as text?

var name = prompt("Enter your name: ");
document.getElementById("paragraph").innerHTML = name;
<p id="paragraph"></p>

Unfortunately I can't use jQuery, so a pure JS solution would be nice.

3
  • 2
    You can use innerText, instead of innerHTML Commented Sep 26, 2018 at 2:13
  • That works perfectly! Please add an answer with that information for quick future reference. Commented Sep 26, 2018 at 2:14
  • There is also textContent. Commented Sep 26, 2018 at 2:42

2 Answers 2

1

You can use innerText, instead of innerHTML

 document.getElementById("paragraph").innerText = name;
Sign up to request clarification or add additional context in comments.

Comments

0

You want to 'escape' the input text before displaying it again.

Your JavaScript would now look like:

var name = escapeHtml(prompt("Enter your name: "));
document.getElementById("paragraph").innerHTML = name;

function escapeHtml(unsafe) {
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
}    

Note: This code snippet is from Can I escape html special chars in javascript?

PSA: Please don't use client-side sanitation of text for anything related to security.

2 Comments

Thanks, but the problem was solved earlier.
Rather than answering with a reference to a duplicate, just mark it as a duplicate. ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.