Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the text content from a contenteditable div through javascript

I want retrieve the text content from a contentEditable div through javascript. What are the options of doing this? I've tried innerHTML but it doesn't work.

like image 312
Suraj Air Avatar asked Aug 29 '10 05:08

Suraj Air


People also ask

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 get the Contenteditable value react?

To listen for changes in a contentEditable element in React, we can listen to the input event on the div. to add a div with the contentEditable attribute set to true . Then we add the onInput prop and pass in a function to log the content of the div, which is stored in the e.

What is Contenteditable div?

Definition and Usage The contenteditable attribute specifies whether the content of an element is editable or not.


2 Answers

Why not use textContent for this:

var contenteditable = document.querySelector('[contenteditable]'),     text = contenteditable.textContent; 

http://jsfiddle.net/E4W8y/1/

like image 67
Mircea Avatar answered Sep 20 '22 22:09

Mircea


Unfortunately, I've found that innerText is the only way to preserve newlines in contenteditable dom nodes. What I'm doing (tested only in chrome at the moment) is this:

 var innerText = editableDiv.innerText  // using innerText here because it preserves newlines  if(innerText[innerText.length-1] === '\n')       innerText = innerText.slice(0,-1)             // get rid of weird extra newline  return innerText 
like image 40
B T Avatar answered Sep 22 '22 22:09

B T