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.
innerHTML = "This is the innerHTML of the <b>div</b> and bla bla bla..."
Cursor is here
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
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