how to get the position of the cursor in an editable div
<p>I have the following function that tracks the cursor position in an editable div:</p>

<pre><code>  function getCaretPosition(editableDiv) {
        var caretPos = 0, containerEl = null, sel, range;
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.rangeCount) {
                range = sel.getRangeAt(0);
                if (range.commonAncestorContainer.parentNode == editableDiv) {
                    caretPos = range.endOffset;
                }
            }
        } else if (document.selection &amp;&amp; document.selection.createRange) {
            range = document.selection.createRange();
            if (range.parentElement() == editableDiv) {
                var tempEl = document.createElement("span");
                editableDiv.insertBefore(tempEl, editableDiv.firstChild);
                var tempRange = range.duplicate();
                tempRange.moveToElementText(tempEl);
                tempRange.setEndPoint("EndToEnd", range);
                caretPos = tempRange.text.length;
            }
        }
        return caretPos-1;
    }
</code></pre>

<p>The issue is that if my editable div has the following html:</p>

<pre><code>hello &lt;span contenteditable='false'&gt;Abderrahmane Benbachir&lt;/span&gt;  
</code></pre>

<p>and I put the cursor next to the span, it starts counting the cursor from 0. Why is this? How do I fix this?</p>
