Bookmarklet for selecting code snippets on Code Review The following code will add to each code block a 'Select Code' button that will select the code belonging to that block. Please review for maintainability.

In order to use this, visit http://codereviewcommunity.github.io/CodeReviewBookmarklet/



javascript: if ($('button').length === 0) { 
  /* Stack Exchange does not do buttons, this does */
  $(".prettyprint").each( function()
  { 
    /* Thank you http://stackoverflow.com/a/2838358/7602 */
    function selectCode(el, win) 
    {
      win = win || window;
      var doc = win.document, sel, range;
      if (win.getSelection &amp;&amp; doc.createRange) 
      {
        sel = win.getSelection();
        range = doc.createRange();
        range.selectNodeContents(el);
        sel.removeAllRanges();
        sel.addRange(range);
      } 
      else if (doc.body.createTextRange) 
      {
        range = doc.body.createTextRange();
        range.moveToElementText(el);
        range.select();
      }
    }

    var buttonText  = 'Select Code',
        length      = buttonText.length,
        codeBlock   = this,
        $link       = $('&lt;button type="button"&gt;' + buttonText + '&lt;/button&gt;&lt;br&gt;').click(function()
        {
          console.log( $(codeBlock).text().substring( length ) );
          selectCode(codeBlock);
        });
    $(codeBlock).prepend( $link );
  });
}


I have tested this on FF and Chrome and it works for me.
You inject the button using jQuery.prepend(), which inserts the button as the first child of the .prettyprint code block.  Therefore, when the bookmarklet is invoked, and it selects the contents of the code block, the "Select Code" button is inadvertently included in the selection.  I recommend using jQuery.before() instead.