Anshuman Dwibhashi Anshuman Dwibhashi - 26 days ago 10
Javascript Question

Contenteditable Div - Cursor position in terms of innerHTML position

I've done my research and come across these questions on StackOverflow where people asked this same question but the thing is that they wanted to get the position either in terms of x and y coordinates or column from the left. I want to know what the position of the cursor is with respect to the div's innerHTML.

For example:

innerHTML = "This is the innerHTML of the <b>div</b> and bla bla bla..."
^
Cursor is here


So the result I want for this case is 44. How to do it ?

Answer Source
var target = document.createTextNode("\u0001");
document.getSelection().getRangeAt(0).insertNode(target);
var position = contentEditableDiv.innerHTML.indexOf("\u0001");
target.parentNode.removeChild(target);

This temporarily inserts a dummy text node containing a non-printable character (\u0001), and then finds the index of that character within the div's innerHTML.

For the most part this leaves the DOM and the current selection unchanged, with one minor possible side effect: if the cursor is in the middle of text from a single text node, that node will be broken up into two consecutive text nodes. Usually that should be harmless, but keep it in mind in the context of your specific application.

UPDATE: Turns out you can merge the consecutive text nodes using Node.normalize().