title: Get selection's offset relative to certain parent node
body: <p>I would like to be able to find out the position (also known as: offset, index) of the user's selection of text (highlighted) within a web page, relative to a particular parent node.</p>
  
  <p>I have been using <a href="https://code.google.com/p/rangy/" rel="nofollow">Rangy</a> to try to help me out, but it doesn't seem to have offset properties built in to the API. Here is what I have so far:</p>
  
  <pre><code>function GetSelectionIndexRelativeTo(parentNodeId) 
  {
      var parentNode = document.getElementById(parentNodeId);
  
      var txt = rangy.getSelection().toString();
      var code = rangy.getSelection().toHtml();
      var len = code.length;
  
      var x1 =         ;       // THIS IS WHAT I REALLY WANT. WHAT DO I DO?
      var x2 = x1 + len;
  
      return {
          text: txt,
          html: code,
          start: x1,
          end: x2,
          length: len
      }
  }
  </code></pre>
  
  <p>To give some examples:</p>
  
  <pre><code>PAGETEXT:      &lt;poem&gt;&lt;title&gt;Galaxy&lt;/title&gt;Twinkle Twinkle Little Star&lt;/poem&gt;
  
  1. SELECTION:  Galaxy
     RELATIVETO: title
     RESULT:     start = 0
  
  2. SELECTION:  Star
     RELATIVETO: poem
     RESULT:     start = 43
  
  3. SELECTION:  Twinkle (the second one)
     RELATIVETO: poem
     RESULT:     start = 28
  </code></pre>