title: Getting and setting of a text selection in a textarea
body: <p>I want to create a textarea where users can select a part of a text, and I will react according to their selection. So I need to</p>
  
  <p>1) get the start and end positions of the selection text</p>
  
  <p>2) get the position of the focus, if it is in the textarea and there is no selection</p>
  
  <p>It seems that the functions to do so are different from an explorer to another. So could anyone tell me what is the approach to do that in Office Add-in?</p>
  
  <p>I have tried the following 2 ways (ie, select a part of the text in <code>myTextarea</code>, click on <code>button</code>, and then debug the code), they don't seem to be the right functions.</p>
  
  <pre><code>(function() {
      "use strict";
  
      Office.initialize = function(reason) {
          $(document).ready(function() {
              app.initialize();
              $('#button').click(showSelection);
          });
      };
  
      function showSelection() {
          // way 1
          console.log(document.selection); // undefined
          document.getElementById("myTextarea").focus();
          var sel = document.selection.createRange(); // Uncaught TypeError: Cannot read property 'createRange' of undefined
          selectedText = sel.text;
          // way 2 
          console.log(document.getElementById("myTextarea").selectionstart); // undefined
          console.log(document.getElementById("myTextarea").selectionend); // undefined
      }
  })();
  </code></pre>
  
  <p>Additionally, it would be great if one could also tell me how to realise the follows by code:</p>
  
  <p>1) select a part of a text, from a start and end positions</p>
  
  <p>2) set the focus at a certain position of the textarea</p>
  
  <p><strong>Edit 1:</strong></p>
  
  <p>I just tried <code>window.getSelection()</code> within my Excel add-in:</p>
  
  <pre><code>function showselection() {
      var a = window.getSelection();
      var b = window.getSelection().toString();
      var c = window.getSelection().getRangeAt(0);
  }
  </code></pre>
  
  <p>After selecting a text in the textarea, and clicking on <code>button</code>, I debugged step by step: the first line made <code>a</code> <code>a = Selection {anchorNode: null, anchorOffset: 0, focusNode: null, focusOffset: 0, is ...</code>; the second line returned <code>""</code>, the third line got an error <code>Home.js:19 Uncaught IndexSizeError: Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index.</code> It looks like the selection has not been successfully caught...</p>
  
  <p>Here is <a href="http://jsbin.com/mayepu/8/edit?html,js,console,output" rel="nofollow">JSBin</a> without Excel add-in frame, which returns almost same results as above.</p>