Is it possible to extract the plaintext from a contenteditable div, including newlines? The jQuery $.text() method strips out newlines, which I need. The solution can use jQuery.
Just set contentEditable="false" . See this answer.
You can add the contenteditable="true" HTML attribute to the element (a <div> for example) that you want to be editable. If you're anticipating a user to only update a word or two within a paragraph, then you could make a <p> itself editable.
Answer: Use the HTML5 contenteditable Attribute You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> element.
Without using extra plugins or writing your own implementation, you can just use both the innerText and textContent attributes (which are equivalent to each other). textContent is supported in all major browsers except IE 6-8, which supports innerText.
var text = x.innerText || x.textContent
http://www.quirksmode.org/dom/w3c_html.html#t07
EDIT: as AgentME points out, this won't preserve the user's whitespace in Firefox. To do that with contenteditable, you'd have to polyfill innerText on Firefox. There are a couple of options I could come up with:
x.innerHTML
, strip out the extra markup whitespace/tags and convert the user's whitespace from <br>
and
to \n
and spaces. Selection
and Range
support. Firefox supports Selection.toString
which has a similar behavior to innerText
, but it only works on the currently-selected text. So what you can do is record the user's current selection, change the selection to be the contents of your contenteditable div, call Selection.toString
, then restore the user's initial selection. Out of the two I personally think the second option would be better in most cases; with the first option you'll either get a quick-and-dirty regex solution or you devolve into implementing a full-blown HTML parser with CSS layout logic. The downside to option 2 is that it's relatively slow, so you may run into issues if you trigger it onchange
or something like that. Demo of option 2 is here.
More info:
With a bit of tweaking, https://github.com/vorushin/jsHtmlToText was just what I needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With