title: Maintain cursor position in contenteditable div
body: <p>First of all, this is similar to these:</p>
  
  <p><a href="https://stackoverflow.com/questions/5767037/editing-iframe-content-in-ie-problem-in-maintaining-text-selection/5770175#5770175">Editing Iframe Content in IE - problem in maintaining text selection</a></p>
  
  <p><a href="https://stackoverflow.com/questions/5951886/how-to-get-caret-position-within-contenteditable-div-with-html-child-elements?answertab=votes#tab-top">How to get caret position within contenteditable div with html child elements?</a></p>
  
  <p>Basically, I'm writing something similar to the new tweet editor in twitter. Inside a <code>div</code> with <code>contentEditable</code> set on, I am parsing the text. When I detect what I think is a URL, I strip that text out and enter into an <code>&lt;a&gt;</code> tag inside the div (e.g. entered message of <code>go to www.google.com</code> becomes <code>Go to &lt;a href='..'&gt;www.google.com&lt;/a&gt;</code>. BUT, the caret position is lost when I do that.</p>
  
  <p>Using the suggestion by @Tim-Down in those other SO posts will only work as long as you don't edit the DOM (as he says). I AM editing the DOM, so the caret position is lost. </p>
  
  <p>Is it possible (ideally without using the Rangy library referenced) to achieve this by working on the current code. </p>
  
  <p>The code that I have at the moment (from the other SO posts):</p>
  
  <pre><code>var saveSelection, restoreSelection;
  if (window.getSelection) {
      // IE 9 and non-IE
      saveSelection = function(win) {
          var sel = win.getSelection(), ranges = [];
          if (sel.rangeCount) {
              for (var i = 0, len = sel.rangeCount; i &lt; len; ++i) {
                  ranges.push(sel.getRangeAt(i));
              }
          }
          return ranges;
      };
  
      restoreSelection = function(win, savedSelection) {
          var sel = win.getSelection();
          sel.removeAllRanges();
          for (var i = 0, len = savedSelection.length; i &lt; len; ++i) {
              sel.addRange(savedSelection[i]);
          }
      };
  } else if (document.selection &amp;&amp; document.selection.createRange) {
      // IE &lt;= 8
      saveSelection = function(win) {
          var sel = win.document.selection;
          return (sel.type != "None") ? sel.createRange() : null;
      };
  
      restoreSelection = function(win, savedSelection) {
          if (savedSelection) {
              savedSelection.select();
          }
      };
  }
  </code></pre>
  
  <p>And I use it like this:</p>
  
  <pre><code>$('div').on('keyup paste', function(e) {
      var ranges = saveSelection(window);
      var newContent = /* Get the new HTML content */;
      $('div').html(newContent);
      restoreSelection(window, ranges);
  });
  </code></pre>