35

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.

6
  • Do you mean each individual item?
    – Gaz Winter
    Commented Jul 12, 2012 at 12:00
  • 2
    you can only trigger the text select event for input and textarea elements.
    – Ram
    Commented Jul 12, 2012 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. Commented Jul 12, 2012 at 12:05
  • 2
    Possible: see this post - stackoverflow.com/questions/985272/…
    – techfoobar
    Commented Jul 12, 2012 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
    Commented Jul 12, 2012 at 12:13

4 Answers 4

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();
    }
});
4
  • 1
    I have no idea how or why this works, but it's perfect! Just what I was looking for. Thank you.
    – David
    Commented Mar 15, 2014 at 4: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
    Commented Feb 16, 2015 at 19:38
  • For Angular users, replace the first line with : $(document).on("click", ".unc_path", function (){
    – boly38
    Commented Jun 25, 2015 at 13:38
  • This is the best answer to the question! Thank you kind sir
    – Valdrinium
    Commented Oct 18, 2017 at 10:40
35

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>

4
  • 3
    I prefer this answer, use CSS whenever possible. Commented Jan 23, 2019 at 2:38
  • According to Can I use, Firefox, Internet Explorer and Safari need the -moz-, -ms- and -webkit- vendor prefixes. Although, MDN notes Safari has issues with -webkit-user-select: all;
    – Dispenser
    Commented May 10, 2019 at 17:00
  • 2
    Great answer. Preferable!
    – Eldshe
    Commented Jul 11, 2021 at 7: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
    Commented Sep 24, 2021 at 7: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();
    });
});​
3
  • 1
    This works well. I made a slight change ... $input.appendTo($(this).parent()); to $input.insertAfter($(this)); Thankyou.
    – MrVimes
    Commented Jul 12, 2012 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... Commented Jul 12, 2012 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
    Commented Jul 12, 2012 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
2
  • hm.. this is only alternative way to identify the element being clicked on. It doesn't help with actually selecting the contents.
    – MrVimes
    Commented Jul 12, 2012 at 12:12
  • oops I missed out the clicking functionality mentioned in your question. Check this --- stackoverflow.com/questions/4165010/…
    – HariHaran
    Commented Jul 12, 2012 at 12:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.