title: Add tags around selected text in an element
body: <p>How can I add <code>&lt;span&gt;</code> tags around selected text within an element?</p>
  
  <p>For example, if somebody highlights "John", I would like to add span tags around it.</p>
  
  <p>HTML</p>
  
  <pre><code>&lt;p&gt;My name is Jimmy John, and I hate sandwiches. My name is still Jimmy John.&lt;/p&gt;
  </code></pre>
  
  <p>JS</p>
  
  <pre><code>function getSelectedText() {
    t = (document.all) ? document.selection.createRange().text : document.getSelection();
  
    return t;
  }
  
  $('p').mouseup(function(){
      var selection = getSelectedText();
      var selection_text = selection.toString();
      console.log(selection);
      console.log(selection_text);
  
      // How do I add a span around the selected text?
  });
  </code></pre>
  
  <p><a href="http://jsfiddle.net/2w35p/" rel="noreferrer">http://jsfiddle.net/2w35p/</a></p>
  
  <p>There is a identical question here: <a href="https://stackoverflow.com/questions/2236982/jquery-select-text-and-add-span-to-it-in-an-paragraph">jQuery select text and add span to it in an paragraph</a>, but it uses outdated jquery methods (e.g. live), and the accepted answer has a bug.</p>