Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  103] [ 3]  / answers: 1 / hits: 25413  / 13 Years ago, mon, april 11, 2011, 12:00:00

I want HTML, for example, <p>, to show show as just that, in plain text, and not interpreted by the browser as an actual tag.



I know JQuery has .html and .text, but how is this done in raw JS?



There are functions like encodeURIComponent that encodes <p> to %3Cp%3E but if I just put that into HTML, it interprets it literally as %3Cp%3E.



So there are also things like &gt; and &lt;, they work but I can't find any JavaScript functions that escapes & unescapes from this.



Is there a correct way to show HTML as text with raw JavaScript?


More From » html

 Answers
45

There's no need to escape the characters. Simply use createTextNode:



var text = document.createTextNode('<p>Stuff</p>');
document.body.appendChild(text);


See a working example here: http://jsfiddle.net/tZ3Xj/.



This is exactly how jQuery does it (line 43 of jQuery 1.5.2):



return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );

[#92820] Friday, April 8, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elainaw

Total Points: 83
Total Questions: 99
Total Answers: 111

Location: South Sudan
Member since Sat, May 27, 2023
1 Year ago
;