2

I have a prettily styled box for editing some raw text:

Screenshot

The box is a <div> with contenteditable="true". I don't want to use textarea because it's so damn annoying to style. Also, the <div> has the wonderful property that it automatically scales to contain the text as the user types.

My problem with the div is that I can't seem to get the raw text out of it. When it's edited by the user, the browser inserts <div>s and <br>s to create line breaks, so when I fetch the text using innerHTML I actually get a bunch of HTML rather than the raw text. If I use innerText instead, it doesn't preserve any of the line breaks and I get this output:

"Foo bar:        PowThis field is:  AlignedWith:           This fieldThree empty lines"

Are there any non-hack, non-workaround solutions provided by the browser to get the text out as it is displayed?


One interesting observation is that I can select the text and copy it into a text editor:

Screenshot

Hubro
  • 56,214
  • 69
  • 228
  • 381
  • This post have some ideas how to: http://stackoverflow.com/questions/16715158/how-to-make-a-content-editable-div-behave-like-a-text-area – Asons Nov 25 '15 at 09:43
  • As you can select and copy, have you tried "select all and copy" using javascript? – Asons Nov 25 '15 at 09:45

2 Answers2

2

This explanation: http://clubajax.org/plain-text-vs-innertext-vs-textcontent/ of the functions plaintext, innerText and textContent explains that there's a diffrence in the way you get the text back depending on your browser.

So i'm afraid the easy answer is: No. It depends on what browser you are using to get the indentations etc.

  • Alright, too bad. I could probably make it work OK using a polyfill, but at this point it seems easier to deal with the textarea styling :) – Hubro Nov 25 '15 at 11:34
1

http://jsfiddle.net/4roq1838/1/

<pre> tag completely save all formating

UPD: innerText is not supported by Firefox

There is a polyfill: https://github.com/duckinator/innerText-polyfill

Demo: http://jsfiddle.net/4roq1838/2/

z1m.in
  • 1,661
  • 13
  • 19