Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get plain text from contenteditable div

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.

like image 654
penguinrob Avatar asked Jul 29 '11 02:07

penguinrob


People also ask

How do I turn off Contenteditable in HTML?

Just set contentEditable="false" . See this answer.

How do you use Contenteditable in Javascript?

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.

How do you make a div Contenteditable?

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.


2 Answers

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:

  1. Start with x.innerHTML, strip out the extra markup whitespace/tags and convert the user's whitespace from <br> and &nbsp; to \n and spaces.
  2. Use Firefox's 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:

  • Mozilla API docs for Selection
  • Speed test of innerText vs Selection.toString
like image 143
mmitchell Avatar answered Oct 07 '22 08:10

mmitchell


With a bit of tweaking, https://github.com/vorushin/jsHtmlToText was just what I needed.

like image 6
penguinrob Avatar answered Oct 07 '22 08:10

penguinrob