1

When I'm trying to change document.documentElement.innerHTML using the innerHTML of a textarea like this:

document.documentElement.innerHTML = document.querySelector('#mytextarea').innerHTML

The innerHTML of #mytextarea is not used as actual HTML to change the DOM, but as plain text.

For example: if the innerHTML of #mytextarea is <p>A paragraph</p>.

Then the document after loading looks like: <p>A paragraph</p> instead of A paragraph

How should I do it so the value inside the #mytextarea could be used to change the DOM? (ex. appending new elements)

TheJSCoder
  • 13
  • 5
  • Please read the [help], especially [ask]. We generally want to see just the question and its related code/circumstances, not pleasantries or extra text. – Heretic Monkey Jun 01 '16 at 20:39
  • 3
    Possible duplicate of [JavaScript get TextArea input via .value or .innerHTML?](http://stackoverflow.com/questions/5314186/javascript-get-textarea-input-via-value-or-innerhtml) – Heretic Monkey Jun 01 '16 at 20:40
  • What is `document.documentElement`? – Barmar Jun 01 '16 at 20:42
  • According to [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement), the Document.documentElement read-only property returns the Element that is the root element of the document (for example, the element for HTML documents). – TheJSCoder Jun 01 '16 at 20:47

2 Answers2

1

Use .value to get the contents of a textarea without it being encoded.

document.getElementById("documentElement").innerHTML = document.querySelector('#mytextarea').value;
<textarea id="mytextarea">
<p>A paragraph</p>
</textarea>
<div id="documentElement">

</div>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    @wirher Why do we need a jsfiddle when we have stack snippets? – Barmar Jun 01 '16 at 20:53
  • Thanks, it worked. I was confused at first then realized I didn't update the value inside my textarea. My question was solved. (btw stackoverflow is very fast, I asked few minutes ago and there are answers instantly.) – TheJSCoder Jun 01 '16 at 20:58
-4

You can easily achieve this without the use of any JavaScript. You just have to insert special characters into your HTML code.

&lt;p&gt;A paragraph&lt;/p&gt;

That weird code will show up as

<p>A paragraph</p>

If you don't know the codes, just use this: HTML Encoder

EDIT: They are called HTML escape characters, or, HTML entities. Here is a list of a lot of them: List

MrStank
  • 314
  • 4
  • 10
  • 2
    This does the exact opposite of what the OP wants. – JJJ Jun 01 '16 at 20:39
  • @Juhana I thought that's what he was asking from this: "How should I do it so it would be used as actual HTML instead of plain text?" – MrStank Jun 01 '16 at 20:43
  • 1
    Thanks for your answer, but what I meant is to use a html string (for example: `""`) to change the DOM, if I use the string above, there would be a image in the document. – TheJSCoder Jun 01 '16 at 20:43