title: Javascript: Select text for copy of all similar elements in HTML document
body: <p>There are a lot of articles published to stackoverflow and in other websites which are relevant to the way of selecting text of <b>ONE</b> element in order to be available for copy.</p>
  
  <p>But I have not found a function which can <strong>SELECT AND HIGHLIGHT</strong> the text of <b>ALL</b> similar elements in an HTML document. For example, to select the text from all <strong>h2</strong> titles.</p>
  
  <p>I tried to modify the function from this <a href="https://stackoverflow.com/questions/12243898/how-to-select-all-text-in-contenteditable-div/12244703#12244703">thread</a> which selects one element.</p>
  
  <p><strong>SELECTING ONE ELEMENT FUNCTION</strong></p>
  
  <pre><code>jQuery.fn.selectText = function(){
     var doc = document;
     var element = this[0];
     console.log(this, element);
     if (doc.body.createTextRange) {
         var range = document.body.createTextRange();
         range.moveToElementText(element);
         range.select();
     } else if (window.getSelection) {
         var selection = window.getSelection();        
         var range = document.createRange();
         range.selectNodeContents(element);
         selection.removeAllRanges();
         selection.addRange(range);
     }
  };
  </code></pre>
  
  <p>Here is the modified version of the above function which performs the selection of all similar elements.</p>
  
  <pre><code>$.fn.selectTextAll = function() {
       var doc = document,
           numElem = this.length,
           elements = this;
  
       if(doc.body.createTextRange) {
           for(i=0; i&lt;numElem; i++) {
               var range = document.body.createTextRange();
               range.moveToElementText(elements[i]);
              range.select();
          }
       } 
       else if(window.getSelection) {
           var selection = window.getSelection();
           selection.removeAllRanges();
           for(i=0; i&lt;numElem; i++) {
               var range = document.createRange();
               range.selectNodeContents(elements[i]);
               selection.addRange(range);
           }
       }
   };
  </code></pre>
  
  <p>The problem is that the above function is working properly in Firefox but in no other browser, Chrome, Safari, Opera, IE+9.</p>
  
  <p>In order to confirm this, you can open <a href="http://jsfiddle.net/zggso0rq/" rel="nofollow noreferrer">this fiddle</a> in all browsers. It is working only in Firefox.</p>
  
  <p>Can anyone give a solution to this?</p>
  
  <p>Thank you for your time</p>