title: Highlight only selected text using jQuery
body: <p>so I'm trying to highlight user selected text. Essentially the user can drag the mouse (while clicked) to select some random text on the page (anything within<code>&lt;p&gt;</code> tags). On mouseup I want to change that text to be highlighted and bold.</p>
  
  <p>The requirements for this are that the text selected and ONLY the text selected gets highlighted. So no matching text in another <code>&lt;p&gt;</code> tag, and no matching text within the same <code>&lt;p&gt;</code> tag.</p>
  
  <p>Now, this is what I have thus far for CSS:</p>
  
  <pre><code>span.highlight {
      background-color: yellow;
      font-weight: bold;
  }
  </code></pre>
  
  <p>And what I have for jQuery:</p>
  
  <pre><code>function getSelected() {
      var selected = '';
  
      if (window.getSelection) {
          selected = window.getSelection().toString();
      } else if (document.getSelection) {
          selected = document.getSelection();
      } else if (document.selection) {
          selected = document.selection.createRange().text;
      }
  }
  
  $(document).ready(function() {
      $('p').live('mouseup', function() {
          var selected = getSelected();
  
          $(this).html($(this).html().replace(selected, '&lt;span class="highlight"&gt;' + selected + '&lt;/span&gt;'));
      });
  });
  </code></pre>
  
  <p>Now this works almost. However it will select the first instance of the selected text and highlight that, which isn't what I want, I want it to select the actual selected text. And it has one more problem, once some text is highlighted, if I select more text that includes part of the highlighted text, it won't change it.</p>
  
  <p>I'm wondering if anyone can help with either of these issues? Thanks in advance.</p>
  
  <p>EDIT:</p>
  
  <p>Sorry, I should have also mentioned that I can't use a plugin. I've taken a look at them and most of them work for my needs quite well, but I can't use them.</p>