As Jordan has already replied, with a good response by the way, you can find the text inside the editor.
However, using childNodes[0]
will not work if there are html tags within the editor that encompass the cursor marker. See an example in this jsfiddle , whose HTML is:
<pre id="editor" contenteditable="true">
“Always pass on what you have learned.” - Yoda
<div>
> {|}
</div>
--
X
</pre>
I've prepared a version using an HTML tag with a special% wrapper that avoids this problem and still allows you to position the cursor without needing a visual element.
The code looks like this:
function setCursor(node, cursorElement) {
var range = document.createRange();
range.setStart(cursorElement, 0);
range.collapse(true);
if (window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
node.focus();
} else if (document.selection && range.select) {
range.select();
}
}
var editor = document.querySelector("#editor");
var button = document.querySelector("button");
button.addEventListener("click", function(e) {
setTimeout(function () {
setCursor(editor, document.querySelector("#cur"));
}, 200);
}, false);
The marker is a id
tag, as in the following snippet:
<pre id="editor" contenteditable="true">
“Always pass on what you have learned.” - Yoda
> <span id="cur"/>
--
X
</pre>
See the Jsfiddle .