# Select text with just one click

I wrote this JS code with some jQuery and got a one-click-text-selection. Maybe someone can improve this code, because I think it's not "clean" and short engough ;) But I don't want to use an input field. Let me know if you have some ideas!

function SelectText(element) {
var doc = document,
text = doc.getElementById(element),
range,
selection;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
}
}
$(function() {$('p').click(function () {
SelectText('autoselect');
});
});


And this is the HTML part:

<div id="autoselect">
<p>Some cool text!</p>
</div>


Here's the code in a fiddle.

You can further improve this by making it a jQuery plugin instead to make it reusable across any element.

non-IE browsers, combined, account for ~60% of users at the time of writing. This means 60% of the time, the two conditions are evaluated since you check for IE first. Instead, reverse the conditions to get it right on the first check 60% of the time.

$.fn.OneClickSelect = function () { return$(this).on('click', function () {

// In here, "this" is the element

var range, selection;

if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(this);
selection.removeAllRanges();