As Jordan has already responded, with a good response by the way, it is possible to locate the text inside the editor.
However, use the childNodes[0]
will not work if there are html tags inside the editor that enclose 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 prepared a version using an HTML tag with a id
special that avoids this problem and still allows to position the cursor without needing a visual element.
The code went 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 tag span
, as in the stretch below:
<pre id="editor" contenteditable="true">
“Always pass on what you have learned.” - Yoda
> <span id="cur"/>
--
X
</pre>
See the Jsfiddle.
http://jsfiddle.net/Td3pV/
– BrunoLM