Lexical provides a powerful selection system that represents the cursor position and selected content.
Selection Types
Lexical has two main selection types:
- RangeSelection - Text cursor or range selection (most common)
- NodeSelection - Selection of entire nodes
Getting Selection
$getSelection
function $getSelection(): BaseSelection | null
Returns the current selection. Must be called within a read or update.
The current selection or null
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
// Work with range selection
}
});
$getPreviousSelection
function $getPreviousSelection(): BaseSelection | null
Returns the previous selection before the current update.
$setSelection
function $setSelection(selection: BaseSelection | null): void
Sets the current selection.
selection
BaseSelection | null
required
The selection to set
RangeSelection
A range selection represents a text cursor or text range with an anchor and focus point.
Creating Range Selections
$createRangeSelection
function $createRangeSelection(): RangeSelection
Creates a new RangeSelection.
A new RangeSelection instance
Type Guard
$isRangeSelection
function $isRangeSelection(x: unknown): x is RangeSelection
Returns true if the value is a RangeSelection.
const selection = $getSelection();
if ($isRangeSelection(selection)) {
console.log('Anchor:', selection.anchor.offset);
console.log('Focus:', selection.focus.offset);
}
Properties
anchor
The anchor point of the selection (where the selection started).
focus
The focus point of the selection (where the selection ended).
The text format to apply to newly inserted text.
style
The inline styles to apply to newly inserted text.
Methods
isCollapsed
Returns true if anchor and focus are at the same position (cursor, not range).
True if the selection is collapsed
const selection = $getSelection();
if ($isRangeSelection(selection)) {
if (selection.isCollapsed()) {
console.log('Cursor position');
} else {
console.log('Text range selected');
}
}
isBackward
Returns true if the selection is backward (focus before anchor).
getNodes
getNodes(): Array<LexicalNode>
Returns all nodes covered by the selection.
Array of nodes in the selection
const selection = $getSelection();
if ($isRangeSelection(selection)) {
const nodes = selection.getNodes();
console.log(`Selected ${nodes.length} nodes`);
}
getTextContent
Returns the text content of the selection.
const selection = $getSelection();
if ($isRangeSelection(selection)) {
const text = selection.getTextContent();
console.log('Selected text:', text);
}
insertText
insertText(text: string): void
Inserts text at the selection, replacing any selected content.
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
selection.insertText('Hello');
}
});
insertNodes
insertNodes(nodes: Array<LexicalNode>): void
Inserts nodes at the selection.
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
const textNode = $createTextNode('Hello');
selection.insertNodes([textNode]);
}
});
removeText
Removes the selected text.
formatText
formatText(formatType: TextFormatType): void
Applies or removes text formatting to the selection.
Format type: ‘bold’, ‘italic’, ‘underline’, ‘strikethrough’, ‘code’, ‘subscript’, ‘superscript’, ‘highlight’
import { FORMAT_TEXT_COMMAND } from 'lexical';
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
selection.formatText('bold');
}
});
hasFormat(type: TextFormatType): boolean
Returns true if all selected text has the specified format.
True if the selection has the format
extract(): Array<LexicalNode>
Extracts the selected nodes from the editor.
insertParagraph
Inserts a paragraph at the selection.
insertLineBreak
insertLineBreak(selectStart?: boolean): void
Inserts a line break at the selection.
Whether to place cursor at the start of the new line
getStartEndPoints
getStartEndPoints(): [PointType, PointType] | null
Returns the start and end points in document order.
points
[PointType, PointType] | null
Array of [start, end] points
Points
Points represent specific positions in the editor.
Creating Points
$createPoint
function $createPoint(
key: NodeKey,
offset: number,
type: 'text' | 'element'
): PointType
The offset within the node
type
'text' | 'element'
required
Whether this is a text or element point
Point Properties
key
The key of the node containing this point.
offset
The offset within the node.
type
Whether this is a text offset or element child index.
Point Methods
getNode
Returns the node at this point.
is(point: PointType): boolean
Returns true if the points are equal.
isBefore
isBefore(point: PointType): boolean
Returns true if this point is before the other point.
set
set(key: NodeKey, offset: number, type: 'text' | 'element'): void
Updates this point’s position.
NodeSelection
A selection of entire nodes (not text ranges).
Creating Node Selections
$createNodeSelection
function $createNodeSelection(): NodeSelection
Creates a new NodeSelection.
A new NodeSelection instance
Type Guard
$isNodeSelection
function $isNodeSelection(x: unknown): x is NodeSelection
Returns true if the value is a NodeSelection.
NodeSelection Methods
add
Adds a node to the selection.
The key of the node to add
delete
delete(key: NodeKey): void
Removes a node from the selection.
clear
Clears all selected nodes.
has
has(key: NodeKey): boolean
Returns true if the node is in the selection.
getNodes
getNodes(): Array<LexicalNode>
Returns all selected nodes.
Selection Utilities
$getTextContent
function $getTextContent(): string
Returns the text content of the current selection.
$selectAll
function $selectAll(): void
Selects all content in the editor.
import { SELECT_ALL_COMMAND } from 'lexical';
editor.update(() => {
$selectAll();
});
$insertNodes
function $insertNodes(nodes: Array<LexicalNode>): void
Inserts nodes at the current selection.
Working with Selection
Check Selection Type
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
console.log('Range selection');
} else if ($isNodeSelection(selection)) {
console.log('Node selection');
} else {
console.log('No selection');
}
});
Get Selected Text
editor.update(() => {
const selection = $getSelection();
if (selection) {
const text = selection.getTextContent();
console.log('Selected:', text);
}
});
Format Selected Text
import { FORMAT_TEXT_COMMAND } from 'lexical';
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
selection.formatText('bold');
}
});
Move Cursor
editor.update(() => {
const root = $getRoot();
const firstChild = root.getFirstChild();
if (firstChild) {
firstChild.selectStart(); // Move cursor to start
}
});
Select Node
editor.update(() => {
const node = $getNodeByKey('some-key');
if (node && $isTextNode(node)) {
node.select(0, node.getTextContentSize());
}
});
import {
SELECT_ALL_COMMAND,
FORMAT_TEXT_COMMAND,
INSERT_PARAGRAPH_COMMAND,
INSERT_LINE_BREAK_COMMAND,
SELECTION_CHANGE_COMMAND
} from 'lexical';
// Listen for selection changes
editor.registerCommand(
SELECTION_CHANGE_COMMAND,
() => {
const selection = $getSelection();
// Handle selection change
return false;
},
COMMAND_PRIORITY_NORMAL
);