I need to get the text (or the whole inner html) of a node, truncated on current caret (text cursor) position in an element with contenteditable
set to true
. I've tried using range.setStart() etc, but I can't make heads and tails of it...
Edit: For clarification, upon some events I want the script to extract text from the beginning of the node that currently has focus to the caret's position (where the blinking vertcal line currently is if an editable field has focus) and store it in a variable. Action similar to what would happen if a user pressed ctrl+shift+home and ctrl+c
Example: Given html:
<span contenteditable=true>Hello, world<br> Good bye, World</span>
And assuming that the caret is between "Good" and "bye", I'd like to retrieve
"Hello, world<br> Good"
I would suggest the following approach:
cloneContents()
method to obtain a DocumentFragment
representing the range's content<div>
or <body>
element and append the fragment to itinnerHTML
Example: http://jsfiddle.net/sUSYG/
Code:
function getHtmlPrecedingSelectionIn(container) {
var html = "";
if (window.getSelection && document.createRange) {
var sel = window.getSelection();
if (sel.rangeCount > 0) {
var selRange = sel.getRangeAt(0);
var range = document.createRange();
range.selectNodeContents(container);
range.setEnd(selRange.startContainer, selRange.startOffset);
var frag = range.cloneContents();
var el = document.createElement("body");
el.appendChild(frag);
html = el.innerHTML;
}
}
return html;
}
Caveats:
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