Phillip Senn
Phillip Senn

Reputation: 47645

setSelectionRange is not a function

This seems so simple, but it's not working:

document.getElementById('test').setSelectionRange(3,3)
<div id="test">test</div>

Google Chrome.

Upvotes: 1

Views: 19297

Answers (3)

Yaroslav
Yaroslav

Reputation: 2438

To make this on <div> you should make it editable:

<div id="test" contenteditable="true">test</div>

Upvotes: 0

Yun
Yun

Reputation: 29

<input id="test" value="hello world" />

var InputElement = $('test')[0] as HTMLInputElement;
InputElement.setSelectionRange(3, 3);

Upvotes: 2

Dacre Denny
Dacre Denny

Reputation: 30390

This is because the 'test' element needs to be an <input/> element. Try revising your HTML as follows:

<input id="test" />

Also consider the following changes to your javascript. With these updates to your code, your javascript should work as expected when there is enough text in your input field. For example, consider this code for selecting "world" in "hello world":

const input = document.getElementById('test');
input.focus();
input.setSelectionRange(6,11);
<input id="test" value="hello world" />

For more information, see the MDN docs for setSelectionRange()

Upvotes: 1

Related Questions