Thoughts of a Serial Tinkerer

Selecting text with JavaScript

Posted on 27 Oct 2011.

Today I was working on a small tool to take some text that a user selects and copy it into a textarea to store ‘notes.’

While I was researching how to do all of that, I figured out how to select arbitrary text on the page and highlight it, as though the user had dragged her cursor and selected it, using JavaScript.

The following snippet uses some jQuery to select an element, but it could just as easily be written without it.

<script type="text/javascript">
  var rng = document.createRange($('p').get(0));
  rng.selectNode($('p').get(0));
  window.getSelection().removeAllRanges();
  window.getSelection().addRange(rng);
</script>