How to select the text of a span on click?

A working demonstration : http://jsfiddle.net/dystroy/V97DJ/

$('.unc_path').click(function (){
    var text = $(this).text();
    var $input = $('<input type=text>');
    $input.prop('value', text);
    $input.insertAfter($(this));
    $input.focus();
    $input.select();
    $(this).hide();
});​

The idea (see comment above) is to dynamically replace the span with an input, only cross-browser way I know to have selected text.

Note that this is only half the road, as you probably want to deselect, style to remove border, etc.

And I must also precise that an input, contrary to a span, cannot span on multiple lines.

I don't think this could/should be used in a real application except in a very specific point.


EDIT : new version : http://jsfiddle.net/dystroy/A5ZEZ/

In this version the text comes back to normal when focus is lost.

$('.unc_path').click(function (){
    var text = $(this).text();
    var $this = $(this);
    var $input = $('<input type=text>');
    $input.prop('value', text);
    $input.insertAfter($(this));
    $input.focus();
    $input.select();
    $this.hide();
    $input.focusout(function(){
        $this.show();
        $input.remove();
    });
});​

It could be implemented with native JavaScript. A working demonstration on jsFiddle. Your code could be like this:

$('.unc_path').click(function (){
    var range, selection;

    if (window.getSelection && document.createRange) {
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(this);
        selection.removeAllRanges();
        selection.addRange(range);
    } else if (document.selection && document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(this);
        range.select();
    }
});

You can use CSS to do this more easily than JS with style="user-select: all;"

add cursor: pointer; so its obvious they can click...

See code snippet:

<p>
Fruit 
<span style="user-select: all; cursor: pointer;">\\apples\oranges\pears</span>
</p>