33

I am looking for a way to select the text inside a span using jquery when the text is clicked on.

For example in the html snippet below, I want the text "\apples\oranges\pears" to become selected when it is clicked on.

<p>Fruit <span class="unc_path">\\apples\oranges\pears</span></p>

I've tried implementing this myself to no avail.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
MrVimes
  • 3,212
  • 10
  • 39
  • 57
  • Do you mean each individual item? – Gaz Winter Jul 12 '12 at 12:00
  • 2
    you can only trigger the `text select` event for input and textarea elements. – Ram Jul 12 '12 at 12:04
  • The simplest solution would probably be to have an input instead of a span. There could be a dynamic replacement but with limitations. – Denys Séguret Jul 12 '12 at 12:05
  • 2
    Possible: see this post - http://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse – techfoobar Jul 12 '12 at 12:05
  • I was hoping there would be a simpler solution than that one tecfoobar, but I'll look into it. Or replacing the text with an uneditable edit box, and making it not look like an edit box. – MrVimes Jul 12 '12 at 12:13
  • this can be done with fairly simple css - https://stackoverflow.com/a/53549766/1536309 – Blair Anderson Nov 30 '18 at 00:59

4 Answers4

51

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();
    }
});
Eugene Manuilov
  • 4,271
  • 8
  • 32
  • 48
  • 1
    I have no idea how or why this works, but it's perfect! Just what I was looking for. Thank you. – David Mar 15 '14 at 04:07
  • 1
    This is the best solution i found for the purpose of simply selecting the text in an element (presumably to copy+paste). It differs from other solutions in that it actually selects the text in an element without replacing it with an input element. I recommend using other solutions (such as the one from "dystroy" above where the element is replaced by a text input) if you want user interactivity. I used it to select, with one click, a complete Wordpress shortcode from a list. Thanks for the really goodvoodoo! – aequalsb Feb 16 '15 at 19:38
  • For Angular users, replace the first line with : `$(document).on("click", ".unc_path", function (){` – boly38 Jun 25 '15 at 13:38
  • This is the best answer to the question! Thank you kind sir – Valdrinium Oct 18 '17 at 10:40
32

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>
Blair Anderson
  • 19,463
  • 8
  • 77
  • 114
  • 2
    I prefer this answer, use CSS whenever possible. – Christhofer Natalius Jan 23 '19 at 02:38
  • According to [Can I use](https://caniuse.com/#feat=user-select-none), Firefox, Internet Explorer and Safari need the `-moz-`, `-ms-` and `-webkit-` vendor prefixes. Although, [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/user-select) notes Safari has issues with `-webkit-user-select: all;` – Dispenser May 10 '19 at 17:00
  • 1
    Great answer. Preferable! – Eldshe Jul 11 '21 at 07:01
  • Sweet! Works fine. (Except for Safari, `all` has full support.) It’s nice how the Range/Selection hassle for interactivity is shifted to CSS. – dakab Sep 24 '21 at 07:09
12

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();
    });
});​
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    This works well. I made a slight change ... $input.appendTo($(this).parent()); to $input.insertAfter($(this)); Thankyou. – MrVimes Jul 12 '12 at 12:18
  • Check the new version : more fun included. With one more line, the text of the input could even replace the original one... – Denys Séguret Jul 12 '12 at 12:20
  • 2
    Even better! I've utilized this (the one that puts it back to normal when focus is lost) in my page. Thanks again :) – MrVimes Jul 12 '12 at 12:24
0

To select the specific Span you need a id to be provided to that span. Else you need to loop through the list of all available span to get it.

Lets take this as Example (have added id attribute)

  <p>Fruit <span class="unc_path" id="span1">\\apples\oranges\pears</span></p> 

The JQuery will be like this

$('span1').text()  // if you want to take the text
$('span1').html() // if you want to take the html
HariHaran
  • 207
  • 1
  • 3
  • hm.. this is only alternative way to identify the element being clicked on. It doesn't help with actually selecting the contents. – MrVimes Jul 12 '12 at 12:12
  • oops I missed out the clicking functionality mentioned in your question. Check this --- http://stackoverflow.com/questions/4165010/use-jquery-to-auto-select-text-inside-a-span-tag-when-clicked – HariHaran Jul 12 '12 at 12:19