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.
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.
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.
Definition and Usage The contenteditable attribute specifies whether the content of an element is editable or not.
Why not use textContent for this:
var contenteditable = document.querySelector('[contenteditable]'), text = contenteditable.textContent;
http://jsfiddle.net/E4W8y/1/
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
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