title: Set Caret Position in 'contenteditable' div that has children
body: <p>I have an HTML structure like this:</p>
  
  <pre><code>&lt;div contenteditable="true"&gt;This is some plain, boring content.&lt;/div&gt;
  </code></pre>
  
  <p>I also have this function that allows me to set the caret position to anywhere I want within the div:</p>
  
  <pre><code>// Move caret to a specific point in a DOM element
  function SetCaretPosition(object, pos)
  {
      // Get key data
      var el = object.get(0); // Strip inner object from jQuery object
      var range = document.createRange();
      var sel = window.getSelection();
  
      // Set the range of the DOM element
      range.setStart(el.childNodes[0], pos);
      range.collapse(true);
  
      // Set the selection point
      sel.removeAllRanges();
      sel.addRange(range);
  }
  </code></pre>
  
  <p>This code works completely fine until I start adding child tags <code>(span, b, i, u, strike, sup, sub)</code> to the div e.g.</p>
  
  <pre><code>&lt;div contenteditable="true"&gt;
      This is some &lt;span class="fancy"&gt;plain&lt;/span&gt;, boring content.
  &lt;/div&gt;
  </code></pre>
  
  <p>Things get more complicated when these child tags end up with child tags of their own e.g.</p>
  
  <pre><code>&lt;div contenteditable="true"&gt;
      This is some &lt;span class="fancy"&gt;&lt;i&gt;plain&lt;/i&gt;&lt;/span&gt;, boring content.
  &lt;/div&gt;
  </code></pre>
  
  <p>Essentially, what happens, is that <code>setStart</code> throws an <code>IndexSizeError</code> when I try to <code>SetCaretPosition</code> to an index higher than the start of a child tag. <code>setStart</code> only works until it reaches the first child tag.</p>
  
  <p>What I need, is for the <code>SetCaretPosition</code> function to handle an unknown number of these child tags (and potentially an unknown number of nested child tags) so that setting the position works in the same way it would if there were no tags.</p>
  
  <p>So for both this: </p>
  
  <pre><code>&lt;div contenteditable="true"&gt;This is some plain, boring content.&lt;/div&gt;
  </code></pre>
  
  <p>and this:</p>
  
  <pre><code>&lt;div contenteditable="true"&gt;
      This is &lt;u&gt;some&lt;/u&gt; &lt;span class="fancy"&gt;&lt;i&gt;plain&lt;/i&gt;&lt;/span&gt;, boring content.
  &lt;/div&gt;
  </code></pre>
  
  <p><code>SetCaretPosition(div, 20);</code> would place the caret before the 'b' in 'boring'.</p>
  
  <p>What is the code I need? Many thanks!</p>