setSelectionRange Moves The Field Caret
Move a text field caret or preselect a span with setSelectionRange after programmatic writes, and read selectionStart, selectionEnd, selectionDirection back.
Code
// Programmatic value writes leave the caret at the start; form code
// uses setSelectionRange to place it deliberately
const field = document.querySelector('#token');
field.value = 'sk_live_9f3ab77c01';
// Caret to the end, where the next keystroke should land
field.focus();
field.setSelectionRange(field.value.length, field.value.length);
console.log('caret at:', field.selectionStart, field.selectionEnd);
// Preselect the prefix so the next input replaces it in one step
field.setSelectionRange(0, 7);
console.log('selected:', field.selectionStart, field.selectionEnd);
// The optional direction decides how Shift+Arrow extends this selection
field.setSelectionRange(3, 8, 'backward');
console.log('direction:', field.selectionDirection);How it works
The file’s state is a handful of top-level bindings: field.
Watch out for
- Ready as-is on a bare install of the language.
- A browser is the runtime here:
documentare not available in Node.
Using it
Look for the caret at:, selected:, direction: prefixes as the file executes; they connect every printed line to the step behind it.
The key statements that remain
field.setSelectionRange(field.value.length, field.value.length);
const field = document.querySelector('#token');
field.setSelectionRange(3, 8, 'backward');
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does setSelectionRange Moves The Field Caret run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.