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

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

Google Chrome.

3 Answers

<input value="hello world" /> var InputElement = $('test')[0] as HTMLInputElement; InputElement.setSelectionRange(3, 3); 
1

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

<input /> 

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 value="hello world" />

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

4

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

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy