How to get a selection of text with JavaScript

October 31st, 2012

JavaScript is a language full of surprises, sometimes it’s dead simple, sometimes it’s complex or counterintuitive. In its early years it was considered as a toy for making wacky DHTML effects on pages, but it actually has elegant and powerful capabilities. Actually most problems rise out of cross-browser issues, and proprietary implementations for the DOM extensions.

To get a selection of text – user selected text by the user that can be copied to the clipboard – can be accessed by JavaScript as easy as this:

document.getSelection()
//document.getSelection().toString()

Wow, but it wouldn’t be this world if there aren’t any cross-browser issues.

The downside: It works for normal text on pages, but it doesn’t  work for input or textarea elements in Firefox or Opera. It does work in Chromium in all cases.

For Firefox or Opera you need this, slightly more complex, code:

// get active Element

var el = document.activeElement, start = el.selectionStart, end = el.selectionEnd;
var selection = el.value.substring(start, end);

Wouldn’t it be nice if Firefox and Opera make document.getSelection()  work like Chromium?

Yes, I guess, but there is another quirk. In Opera you can have multiple selections, you can select text in a texarea field, and leave that selected while you copy text somewhere else. I’m not sure why that is, sometimes confusing sometimes it’s convenient.

Leave a Reply