1

How do I get the value of a contenteditable element?

Right now I just use innerHTML to get the content of the element, which would result carriage returns as <br> tags, so I need to convert <br> tags to \n right now.

Is there another more proper way to get the value from a contenteditable element that I just don't know about?

Update:

In a textarea element when you get the value e.g. textarea.value the content is intact, like the carriage returns. Is there a similar way to get value from a contenteditable element or I am forced to replace values?

content.innerHTML.replace(/<br\s*[\/]?>/gi, "\n")

element.textContent only gets the text, carriage returns not included. So this does not solve my problem.

Jo E.
  • 7,822
  • 14
  • 58
  • 94
  • 1
    You might need to check **[this link](http://stackoverflow.com/questions/3455931/extracting-text-from-a-contenteditable-div)** – Guruprasad J Rao Mar 18 '15 at 09:32
  • possible duplicate of [get the text content from a contenteditable div through javascript](http://stackoverflow.com/questions/3593626/get-the-text-content-from-a-contenteditable-div-through-javascript) – JohnIdol Mar 18 '15 at 09:49
  • @JohnIdol I already saw that question and the answers do not answer this question. But it did answer my other question. – Jo E. Mar 18 '15 at 10:05
  • 1
    You need to consider line breaks implied by block elements as well. For example, your contenditable element's `innerHTML` could be `

    First paragraph

    Second paragraph

    `.
    – Tim Down Mar 18 '15 at 14:49

1 Answers1

0

If you're looking to let users edit text the only clean solution is to go with a text area as you figured out yourself.

If for some reason you can't or you don't wanna use a textarea you have write your own bit of code that will convert those <br> into carriage returns. There is no automatic way of doing this because there could be all sorts of markup in there.

JohnIdol
  • 48,899
  • 61
  • 158
  • 242