title: how to get the caret position of a contenteditable div which contains images
body: <p>I have this contentedittable div</p>
  
  <pre><code>&lt;div contenteditable="true" id="text"&gt;minubyv&lt;img src="images/smiley/Emoji Smiley-01.png" class="emojiText" /&gt;iubyvt&lt;/div&gt;
  </code></pre>
  
  <p>Here is an image description of the code output
  <a href="https://i.stack.imgur.com/2SydY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2SydY.png" alt="enter image description here"></a></p>
  
  <p>so I want to get the caret position of the div and lets assume that the cursor is after the last character. And this is my code for getting the caret position</p>
  
  <pre><code>function getCaretPosition(editableDiv) {
    var caretPos = 0,
      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;
  }
  
  var update = function() {
    console.log(getCaretPosition(this));
  };
  $('#text').on("mousedown mouseup keydown keyup", update);
  </code></pre>
  
  <p>But the problem is that it returns <code>6</code> instead of <code>14</code>. The caret position goes back to <code>0</code> after the image. Please is there a way I can get the caret position to be <code>14</code> in this case.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I want to also insert some element starting from the caret position. so this is my function to do that</p>
  
  <pre><code>selectStart = 0;
  var update = function() {
    selectStart = getCaretPosition(this);
  };
  function insertEmoji(svg){
      input = $('div#text').html();
      beforeCursor = input.substring(0, selectStart);
      afterCursor = input.substring(selectStart, input.length);
      emoji = '&lt;img src="images/smiley/'+svg+'.png" class="emojiText" /&gt;';
      $('div#text').html(beforeCursor+emoji+afterCursor);
  }
  </code></pre>