How to get the selected text on a page with Javascript

There are lots of reasons to need the currently selected text on a page in Javascript to do some manipulation. Unfortunately, there are about as many ways to get it as there are browsers.

I initially looked at the document.selection object, but it only works in Internet Explorer. After a bunch of heartache and searching, I came across the quirksmode site, which BTW, I highly recommend for anyone interested in Javascript/DOM.

The author offers a function that gives you some nice cross browser functionality. I’ve modified it to simply return the selected text as a string, instead of output it to the page.

function getSel() {
	if (window.getSelection) {
		return window.getSelection();
	} else if (document.getSelection) {
		return document.getSelection();
	} else if (document.selection) {
		return document.selection.createRange().text;
	}
	return;
}


Could it get any simpler?