37

I'm having this annoying problem, I can't seem to get the starting and ending index of the selected text in a textarea, all I get is undefined like this:

$('#myarea').selectionStart; // return undefined

Did I do something wrong?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Dennis
  • 3,448
  • 8
  • 38
  • 45

2 Answers2

86

Try:

$('#myarea')[0].selectionStart;

Why? A jQuery selector does not return the actual DOM elements but the wrapped jQuery collection. jQuery makes the actual DOM elements accessible as an array, so if you wanted to use the 1st matched element (and in this case, the only one, since it's by ID), you would do the above.

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • 9
    Holy crap useful obscure knowledge! Thanks – MrBrightside Nov 10 '12 at 00:30
  • 2
    This was the final piece of my morning JS puzzle. You sir, are a life saver! By the way, for anyone wanting to use this in order to automatically replace certain characters in an input field while maintaining the caret position: remember to apply the [0] to your "setSelectionRange" as well. – Raymond Mar 17 '16 at 09:14
18

Since jQuery version 1.6, you can use .prop() method:

Get:

// always start at 0

var start = $('#myarea').prop('selectionStart');
var end = $('#myarea').prop('selectionEnd');

Set:

$('#myarea').prop('selectionStart', 10);
$('#myarea').prop('selectionEnd', 15);

// or short hand by

$('#myarea').prop({
    'selectionStart': 10,
    'selectionEnd': 15
});
Tân
  • 1
  • 15
  • 56
  • 102
  • 1
    Don't want to be pushy, but what advantages does this have over the native property? O.o There aren't any compatibility issues with the native one and I only see it being even longer and surely also slower.. – Dennis98 Sep 28 '16 at 13:41