7

I am developing some kind of online html editor and I have a problem with getting the content of a textarea with jQuery.

The Textarea element is like this:

<textarea id="myText"><b>&lt;p&gt;TEST&lt;/p&gt;</b></textarea>

So it is a mixture of escaped and unescaped text. However, the browser shows the textarea like this, which is also something that I don't want :

<b><p>TEST</p></b>

I want to get the inner html of the textarea as it is. If I try .html(), it escapes all the tags and if I try .val(), it decodes the escaped tags. You can see the behavior at http://jsfiddle.net/hnBte/

How can I get the pure content with Javascript and optionally, how can I make the textarea show the content as it is?

Thanks

keeri
  • 809
  • 2
  • 13
  • 19
Ahmet Eren Başak
  • 493
  • 1
  • 4
  • 14

5 Answers5

8

I found this a really interesting question, so I did some research: I tried all javascript and jQuery functions to see what I would get, but nothing worked. You can only get completely unparsed or completely parsed html.

I also stumbled upon this SO-question, that also confirms that, sadly, it just can't be done: Getting raw text content of HTML element with HTML uninterpreted.

Community
  • 1
  • 1
Terrabythia
  • 2,031
  • 3
  • 19
  • 29
4

For anyone asking this in 2021.. My solution was to take the text in place it in a different textarea using .innerHTML, then using document.getElementById("area").textContent to get the plain text, without encoding or escaping.

anitag95
  • 307
  • 2
  • 16
0

Try .text() method in jQuery. http://api.jquery.com/text/

Chamara Keragala
  • 5,627
  • 10
  • 40
  • 58
0

Can you not use the standard JavaScript .innerHTML?

Here is a related post about the differences between JavaScript .innerHTML and JQuery .HTML() https://stackoverflow.com/a/3563136/2099977

Community
  • 1
  • 1
Paul Welbourne
  • 1,063
  • 10
  • 16
  • That has the same effect as jQuery's .html() – Terrabythia Apr 27 '13 at 14:07
  • `innerHTML` returns the same value as `.html()` while `textContent` returns the decoded form like `.val()` – Ahmet Eren Başak Apr 27 '13 at 14:08
  • I'm not sure you can do this since the browser has already interpreted the mark-up and the raw <p>TEST</p> values have been converted to html. I think you can only get the whole contents as HTML using `.val()` or the whole contents HTMLencoded using `.innerHTML`. – Paul Welbourne Apr 27 '13 at 14:21
0

Capture the input as the user enters it, or when you load it from an external source.

mtyson
  • 8,196
  • 16
  • 66
  • 106