Selection API: read and set the selection
Work with text selection within the editor.
Reaching the editor instance
The methods below run on the editor you created with new Blok(). They are available once editor.isReady resolves.
// You already hold the instance returned by the constructor.
const editor = new Blok({ holder: 'editor' });
await editor.isReady;
// Call any API method on it.
editor.caret.setToLastBlock('end');Methods
selection.findParentTag(tagName, className?)
HTMLElement | nullFind the parent element of the current selection matching the tag and optionally class.
When to use
The standard way for inline tools to detect whether the cursor is already inside their tag (e.g. an <a> for a link).
const bold = editor.selection.findParentTag('B');
if (bold) {
console.log('Selection is inside bold text');
}
const link = editor.selection.findParentTag('A', 'external-link');selection.expandToTag(node)
voidExpand selection to cover the entire element.
When to use
Grow the selection to wrap a whole element — typically to select an existing mark before replacing or removing it.
const element = editor.selection.findParentTag('B');
if (element) {
editor.selection.expandToTag(element);
// Now entire bold element is selected
}selection.setFakeBackground()
voidSet a fake background to imitate selection when focus moves away. Useful for inline tools.
When to use
Keep a visible 'selection' highlight while focus moves to your tool's input. Always pair with a later removeFakeBackground().
// Save selection visual before opening a modal
editor.selection.setFakeBackground();
// Open modal - selection stays visually highlightedselection.removeFakeBackground()
voidRemove the fake background selection.
When to use
Tears down the fake highlight set by setFakeBackground(); call when your inline UI closes.
// After closing modal
editor.selection.removeFakeBackground();selection.clearFakeBackground()
voidClear all fake background state - both DOM elements and internal flags.
When to use
Heavier reset than removeFakeBackground() — clears both DOM and internal flags if state got out of sync.
// Full cleanup after undo/redo
editor.selection.clearFakeBackground();selection.save()
voidSave the current selection range to restore later.
When to use
Stash the current range before focus leaves the document (e.g. opening a dialog), then bring it back with restore().
// Save selection before moving focus
editor.selection.save();
// Do something that moves focus away...
// Restore selection
editor.selection.restore();selection.restore()
voidRestore a previously saved selection range.
When to use
Re-applies the range saved by save() — the round-trip that lets inline tools survive a focus change.
editor.selection.save();
// ... operations that move focus ...
editor.selection.restore();