Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert HTML as Text

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?

like image 824
foobar Avatar asked Apr 11 '11 05:04

foobar


People also ask

Can you use HTML in text?

One of HTML's main jobs is to give text structure so that a browser can display an HTML document the way its developer intends. This article explains the way HTML can be used to structure a page of text by adding headings and paragraphs, emphasizing words, creating lists, and more.

How do I insert HTML into text in Outlook?

You can inject HTML code into the message body via the Insert as Text option; tab Insert-> (Attach) File-> select the created htm-file-> press the down arrow on the Insert button-> Insert as Text.

How do I put an HTML in the body of an email?

You can embed HTML in email with the 'Insert as Text' option. Select 'Insert' > Attach File > Select the htm. file > Click on 'Insert' dropdown bar > Select 'Insert as Text'.


2 Answers

You can use aslo innerText from most of DOM elements:

document.getElementById('some').innerText = "There can be <b> even HTML tags </b>";

The tags will not be formatted. You can aslo use \n for new line and more codes (\t, \u2623...). If you want aslo to use fixed-size characters you can use easy <pre> tag.

like image 132
PsychoX Avatar answered Oct 05 '22 23:10

PsychoX


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 ) );
like image 27
David Tang Avatar answered Oct 05 '22 23:10

David Tang