I have this bit of code, which I use to get the cursor's position in an editable div :
function getMeCurPos(element){
if (typeof window.getSelection != "undefined") {
var range = window.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
return caretOffset;
}
}
The problem is that, the caretOffset returned only counts the textual contents and not the html tags. For eg :
Consider this string in my editable div :
Hey <b>jony</b>, whats goin on in the | party
*Cursor is denoted by |
character.
Doing getMeCurPos(ele) returns : 30
but it should return 37
. It doesn't count b
tags
To select all text inside an element such as DIV, we can simply use JavaScript document. createRange() method to create a range, and than using range. selectNodeContents() we can set node range (start and end), after which use selection. addRange() to select the range of the element.
The DOM Input select() method selects all the text content of a textarea or an input element which contains the text field. Syntax: element. select();
The * selector selects all elements. The * selector can also select all elements inside another element (See "More Examples").
You may create a temp div
in which you can put your preCaretRange
and where you can use textContent
or innerText
on it. This won't take the HTML length, but the text around it.
function getMeCurPos(element){
if (typeof window.getSelection != "undefined") {
var range = window.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
var temp = document.createElement("div");
temp.innerHTML = preCaretRange.toString();
var sanitized = temp.textContent || temp.innerText;
caretOffset = sanitized.length;
return caretOffset;
}
}
See this fiddle
For getting the selection both as text and as DOM nodes you can use the cloneContents()
in the Javascript selection-range.
HTML as below
function getMeCurPos(element) {
if (typeof window.getSelection != "undefined") {
var range = window.getSelection();
cloned.innerHTML = '';
for (let i = 0; i < range.rangeCount; i++) {
cloned.append(range.getRangeAt(i).cloneContents());
}
var sanitized = cloned.innerHTML;
caretOffset = sanitized.length;
return caretOffset;
}
}
<p contenteditable="true" id="test" onclick="alert(getMeCurPos(this))">Test1<br>Test2<br>Test3<br>Test4</p>
<br>
Cloned: <span id="cloned"></span>
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