Selection (engine/model)
@ckeditor/ckeditor5-engine/src/model/selection
Selection is a set of ranges. It has a direction specified by its anchor and focus (it can be forward or backward). Additionally, selection may have its own attributes (think – whether text typed in in this selection should have those attributes – e.g. whether you type a bolded text).
Filtering
Properties
-
Selection anchor. Anchor is the position from which the selection was started. If a user is making a selection by dragging the mouse, the anchor is where the user pressed the mouse button (the beginning of the selection).
Anchor and
focusdefine the direction of the selection, which is important when expanding/shrinking selection. The focus moves, while the anchor should remain in the same place.Anchor is always set to the start or end position of the last of selection's ranges. Whether it is the
startorenddepends on the specifiedoptions.backward. See thesetTo()method.May be set to
nullif there are no ranges in the selection. -
Selection focus. Focus is the position where the selection ends. If a user is making a selection by dragging the mouse, the focus is where the mouse cursor is.
May be set to
nullif there are no ranges in the selection. -
Whether the selection is collapsed. Selection is collapsed when there is exactly one range in it and it is collapsed.
-
Returns the number of ranges in the selection.
-
List of attributes set on current selection.
-
Specifies whether the last added range was added as a backward or forward range.
Methods
-
Creates a new selection instance based on the given selectable or creates an empty selection if no arguments were passed.
// Creates empty selection without ranges. const selection = writer.createSelection(); // Creates selection at the given range. const range = writer.createRange( start, end ); const selection = writer.createSelection( range ); // Creates selection at the given ranges const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ]; const selection = writer.createSelection( ranges ); // Creates selection from the other selection. // Note: It doesn't copy selection attributes. const otherSelection = writer.createSelection(); const selection = writer.createSelection( otherSelection ); // Creates selection from the given document selection. // Note: It doesn't copy selection attributes. const documentSelection = model.document.selection; const selection = writer.createSelection( documentSelection ); // Creates selection at the given position. const position = writer.createPositionFromPath( root, path ); const selection = writer.createSelection( position ); // Creates selection at the given offset in the given element. const paragraph = writer.createElement( 'paragraph' ); const selection = writer.createSelection( paragraph, offset ); // Creates a range inside an element which starts before the // first child of that element and ends after the last child of that element. const selection = writer.createSelection( paragraph, 'in' ); // Creates a range on an item which starts before the item and ends // just after the item. const selection = writer.createSelection( paragraph, 'on' );Selection's constructor allow passing additional options (
'backward') as the last argument.// Creates backward selection. const selection = writer.createSelection( range, { backward: true } );Parameters
args : tuple
-
containsEntireContent( element ) → booleanmodule:engine/model/selection~Selection#containsEntireContentChecks whether the selection contains the entire content of the given element. This means that selection must start at a position touching the element's start and ends at position touching the element's end.
By default, this method will check whether the entire content of the selection's current root is selected. Useful to check if e.g. the user has just pressed Ctrl + A.
Parameters
element : Element-
Defaults to
...
Returns
boolean
-
inherited
delegate( events ) → EmitterMixinDelegateChainmodule:engine/model/selection~Selection#delegateDelegates selected events to another
Emitter. For instance:emitterA.delegate( 'eventX' ).to( emitterB ); emitterA.delegate( 'eventX', 'eventY' ).to( emitterC );then
eventXis delegated (fired by)emitterBandemitterCalong withdata:emitterA.fire( 'eventX', data );and
eventYis delegated (fired by)emitterCalong withdata:emitterA.fire( 'eventY', data );Parameters
events : Array<string>Event names that will be delegated to another emitter.
Returns
-
inherited
fire( eventOrInfo, args ) → GetEventInfo<TEvent>[ 'return' ]module:engine/model/selection~Selection#fireFires an event, executing all callbacks registered for it.
The first parameter passed to callbacks is an
EventInfoobject, followed by the optionalargsprovided in thefire()method call.Type parameters
Parameters
eventOrInfo : GetNameOrEventInfo<TEvent>The name of the event or
EventInfoobject if event is delegated.args : TEvent[ 'args' ]Additional arguments to be passed to the callbacks.
Returns
GetEventInfo<TEvent>[ 'return' ]By default the method returns
undefined. However, the return value can be changed by listeners through modification of theevt.return's property (the event info is the first param of every callback).
-
getAttribute( key ) → unknownmodule:engine/model/selection~Selection#getAttributeGets an attribute value for given key or
undefinedif that attribute is not set on the selection.Parameters
key : stringKey of attribute to look for.
Returns
unknownAttribute value or
undefined.
-
getAttributeKeys() → IterableIterator<string>module:engine/model/selection~Selection#getAttributeKeysReturns iterable that iterates over this selection's attribute keys.
Returns
IterableIterator<string>
-
getAttributes() → IterableIterator<tuple>module:engine/model/selection~Selection#getAttributesReturns iterable that iterates over this selection's attributes.
Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value. This format is accepted by native
Mapobject and also can be passed inNodeconstructor.Returns
IterableIterator<tuple>
-
getFirstPosition() → null | Positionmodule:engine/model/selection~Selection#getFirstPosition -
getFirstRange() → null | Rangemodule:engine/model/selection~Selection#getFirstRange -
getLastPosition() → null | Positionmodule:engine/model/selection~Selection#getLastPosition -
getLastRange() → null | Rangemodule:engine/model/selection~Selection#getLastRange -
Returns an iterable object that iterates over copies of selection ranges.
Returns
IterableIterator<Range>
-
getSelectedBlocks() → IterableIterator<Element>module:engine/model/selection~Selection#getSelectedBlocksGets elements of type "block" touched by the selection.
This method's result can be used for example to apply block styling to all blocks covered by this selection.
Note:
getSelectedBlocks()returns blocks that are nested in other non-block elements but will not return blocks nested in other blocks.In this case the function will return exactly all 3 paragraphs (note:
<blockQuote>is not a block itself):<paragraph>[a</paragraph> <blockQuote> <paragraph>b</paragraph> </blockQuote> <paragraph>c]d</paragraph>In this case the paragraph will also be returned, despite the collapsed selection:
<paragraph>[]a</paragraph>In such a scenario, however, only blocks A, B & E will be returned as blocks C & D are nested in block B:
[<blockA></blockA> <blockB> <blockC></blockC> <blockD></blockD> </blockB> <blockE></blockE>]If the selection is inside a block all the inner blocks (A & B) are returned:
<block> <blockA>[a</blockA> <blockB>b]</blockB> </block>Special case: Selection ignores first and/or last blocks if nothing (from user perspective) is selected in them.
// Selection ends and the beginning of the last block. <paragraph>[a</paragraph> <paragraph>b</paragraph> <paragraph>]c</paragraph> // This block will not be returned // Selection begins at the end of the first block. <paragraph>a[</paragraph> // This block will not be returned <paragraph>b</paragraph> <paragraph>c]</paragraph> // Selection begings at the end of the first block and ends at the beginning of the last block. <paragraph>a[</paragraph> // This block will not be returned <paragraph>b</paragraph> <paragraph>]c</paragraph> // This block will not be returnedReturns
IterableIterator<Element>
-
getSelectedElement() → null | Elementmodule:engine/model/selection~Selection#getSelectedElement -
hasAttribute( key ) → booleanmodule:engine/model/selection~Selection#hasAttributeChecks if the selection has an attribute for given key.
Parameters
key : stringKey of attribute to check.
Returns
booleantrueif attribute with given key is set on selection,falseotherwise.
-
inherited
is( type ) → this is Element | RootElementmodule:engine/model/selection~Selection#is:ELEMENTChecks whether the object is of type
Elementor its subclass.element.is( 'element' ); // -> true element.is( 'node' ); // -> true element.is( 'model:element' ); // -> true element.is( 'model:node' ); // -> true element.is( 'view:element' ); // -> false element.is( 'documentSelection' ); // -> falseAssuming that the object being checked is an element, you can also check its name:
element.is( 'element', 'imageBlock' ); // -> true if this is an <imageBlock> element text.is( 'element', 'imageBlock' ); -> falseParameters
type : 'element' | 'model:element'
Returns
this is Element | RootElement
-
Checks whether the object is of type
RootElement.rootElement.is( 'rootElement' ); // -> true rootElement.is( 'element' ); // -> true rootElement.is( 'node' ); // -> true rootElement.is( 'model:rootElement' ); // -> true rootElement.is( 'model:element' ); // -> true rootElement.is( 'model:node' ); // -> true rootElement.is( 'view:element' ); // -> false rootElement.is( 'documentFragment' ); // -> falseAssuming that the object being checked is an element, you can also check its name:
rootElement.is( 'rootElement', '$root' ); // -> same as aboveParameters
type : 'rootElement' | 'model:rootElement'
Returns
this is RootElement
-
Checks whether the object is of type
Text.text.is( '$text' ); // -> true text.is( 'node' ); // -> true text.is( 'model:$text' ); // -> true text.is( 'model:node' ); // -> true text.is( 'view:$text' ); // -> false text.is( 'documentSelection' ); // -> falseNote: Until version 20.0.0 this method wasn't accepting
'$text'type. The legacy'text'type is still accepted for backward compatibility.Parameters
type : '$text' | 'model:$text'
Returns
this is Text
-
Checks whether the object is of type
Rangeor its subclass.range.is( 'range' ); // -> true range.is( 'model:range' ); // -> true range.is( 'view:range' ); // -> false range.is( 'documentSelection' ); // -> falseParameters
type : 'range' | 'model:range'
Returns
-
Checks whether the object is of type
LivePosition.livePosition.is( 'position' ); // -> true livePosition.is( 'model:position' ); // -> true livePosition.is( 'liveposition' ); // -> true livePosition.is( 'model:livePosition' ); // -> true livePosition.is( 'view:position' ); // -> false livePosition.is( 'documentSelection' ); // -> falseParameters
type : 'livePosition' | 'model:livePosition'
Returns
this is LivePosition
-
inherited
is( type ) → this is Position | LivePositionmodule:engine/model/selection~Selection#is:POSITIONChecks whether the object is of type
Positionor its subclass.position.is( 'position' ); // -> true position.is( 'model:position' ); // -> true position.is( 'view:position' ); // -> false position.is( 'documentSelection' ); // -> falseParameters
type : 'position' | 'model:position'
Returns
this is Position | LivePosition
-
Checks whether the object is of type
LiveRange.liveRange.is( 'range' ); // -> true liveRange.is( 'model:range' ); // -> true liveRange.is( 'liveRange' ); // -> true liveRange.is( 'model:liveRange' ); // -> true liveRange.is( 'view:range' ); // -> false liveRange.is( 'documentSelection' ); // -> falseParameters
type : 'liveRange' | 'model:liveRange'
Returns
this is LiveRange
-
Checks whether the object is of type
RootElementand has the specifiedname.rootElement.is( 'rootElement', '$root' );Type parameters
N : extends string
Parameters
type : 'rootElement' | 'model:rootElement'name : N
Returns
boolean
-
Checks whether the object is of type
Elementor its subclass and has the specifiedname.element.is( 'element', 'imageBlock' ); // -> true if this is an <imageBlock> element text.is( 'element', 'imageBlock' ); -> falseType parameters
N : extends string
Parameters
type : 'element' | 'model:element'name : N
Returns
boolean
-
Checks whether the object is of type
TextProxy.textProxy.is( '$textProxy' ); // -> true textProxy.is( 'model:$textProxy' ); // -> true textProxy.is( 'view:$textProxy' ); // -> false textProxy.is( 'range' ); // -> falseNote: Until version 20.0.0 this method wasn't accepting
'$textProxy'type. The legacy'textProxt'type is still accepted for backward compatibility.Parameters
type : '$textProxy' | 'model:$textProxy'
Returns
this is TextProxy
-
inherited
is( type ) → this is DocumentSelectionmodule:engine/model/selection~Selection#is:DOCUMENT_SELECTIONChecks whether the object is of type
DocumentSelection.selection.is( 'selection' ); // -> true selection.is( 'documentSelection' ); // -> true selection.is( 'model:selection' ); // -> true selection.is( 'model:documentSelection' ); // -> true selection.is( 'view:selection' ); // -> false selection.is( 'element' ); // -> false selection.is( 'node' ); // -> falseParameters
type : 'documentSelection' | 'model:documentSelection'
Returns
this is DocumentSelection
-
inherited
is( type ) → this is Selection | DocumentSelectionmodule:engine/model/selection~Selection#is:SELECTIONChecks whether the object is of type
SelectionorDocumentSelection.selection.is( 'selection' ); // -> true selection.is( 'model:selection' ); // -> true selection.is( 'view:selection' ); // -> false selection.is( 'range' ); // -> falseParameters
type : 'selection' | 'model:selection'
Returns
this is Selection | DocumentSelection
-
inherited
is( type ) → this is DocumentFragmentmodule:engine/model/selection~Selection#is:DOCUMENT_FRAGMENTChecks whether the object is of type
DocumentFragment.docFrag.is( 'documentFragment' ); // -> true docFrag.is( 'model:documentFragment' ); // -> true docFrag.is( 'view:documentFragment' ); // -> false docFrag.is( 'element' ); // -> false docFrag.is( 'node' ); // -> falseParameters
type : 'documentFragment' | 'model:documentFragment'
Returns
this is DocumentFragment
-
inherited
is( type ) → this is Node | Text | Element | RootElementmodule:engine/model/selection~Selection#is:NODEChecks whether the object is of type
Nodeor its subclass.This method is useful when processing model objects that are of unknown type. For example, a function may return a
DocumentFragmentor aNodethat can be either a text node or an element. This method can be used to check what kind of object is returned.someObject.is( 'element' ); // -> true if this is an element someObject.is( 'node' ); // -> true if this is a node (a text node or an element) someObject.is( 'documentFragment' ); // -> true if this is a document fragmentSince this method is also available on a range of view objects, you can prefix the type of the object with
model:orview:to check, for example, if this is the model's or view's element:modelElement.is( 'model:element' ); // -> true modelElement.is( 'view:element' ); // -> falseBy using this method it is also possible to check a name of an element:
imageElement.is( 'element', 'imageBlock' ); // -> true imageElement.is( 'element', 'imageBlock' ); // -> same as above imageElement.is( 'model:element', 'imageBlock' ); // -> same as above, but more preciseParameters
type : 'node' | 'model:node'
Returns
this is Node | Text | Element | RootElement
-
isEqual( otherSelection ) → booleanmodule:engine/model/selection~Selection#isEqualChecks whether this selection is equal to the given selection. Selections are equal if they have the same directions, the same number of ranges and all ranges from one selection equal to ranges from the another selection.
Parameters
otherSelection : Selection | DocumentSelectionSelection to compare with.
Returns
booleantrueif selections are equal,falseotherwise.
-
inherited
listenTo( emitter, event, callback, [ options ] ) → voidmodule:engine/model/selection~Selection#listenTo:BASE_EMITTERRegisters a callback function to be executed when an event is fired in a specific (emitter) object.
Events can be grouped in namespaces using
:. When namespaced event is fired, it additionally fires all callbacks for that namespace.// myEmitter.on( ... ) is a shorthand for myEmitter.listenTo( myEmitter, ... ). myEmitter.on( 'myGroup', genericCallback ); myEmitter.on( 'myGroup:myEvent', specificCallback ); // genericCallback is fired. myEmitter.fire( 'myGroup' ); // both genericCallback and specificCallback are fired. myEmitter.fire( 'myGroup:myEvent' ); // genericCallback is fired even though there are no callbacks for "foo". myEmitter.fire( 'myGroup:foo' );An event callback can stop the event and set the return value of the
firemethod.Type parameters
Parameters
emitter : EmitterThe object that fires the event.
event : TEvent[ 'name' ]The name of the event.
callback : GetCallback<TEvent>The function to be called on event.
[ options ] : GetCallbackOptions<TEvent>Additional options.
Returns
void
-
Stops executing the callback on the given event. Shorthand for
this.stopListening( this, event, callback ).Parameters
event : stringThe name of the event.
callback : FunctionThe function to stop being called.
Returns
void
-
Registers a callback function to be executed when an event is fired.
Shorthand for
this.listenTo( this, event, callback, options )(it makes the emitter listen on itself).Type parameters
Parameters
event : TEvent[ 'name' ]The name of the event.
callback : GetCallback<TEvent>The function to be called on event.
[ options ] : GetCallbackOptions<TEvent>Additional options.
Returns
void
-
Registers a callback function to be executed on the next time the event is fired only. This is similar to calling
onfollowed byoffin the callback.Type parameters
Parameters
event : TEvent[ 'name' ]The name of the event.
callback : GetCallback<TEvent>The function to be called on event.
[ options ] : GetCallbackOptions<TEvent>Additional options.
Returns
void
-
removeAttribute( key ) → voidmodule:engine/model/selection~Selection#removeAttributeRemoves an attribute with given key from the selection.
If given attribute was set on the selection, fires the event-change:range event with removed attribute key.
Parameters
key : stringKey of attribute to remove.
Returns
void
Fires
-
setAttribute( key, value ) → voidmodule:engine/model/selection~Selection#setAttributeSets attribute on the selection. If attribute with the same key already is set, it's value is overwritten.
If the attribute value has changed, fires the event-change:range event with the attribute key.
Parameters
key : stringKey of attribute to set.
value : unknownAttribute value.
Returns
void
Fires
-
setFocus( itemOrPosition, [ offset ] ) → voidmodule:engine/model/selection~Selection#setFocusMoves
focusto the specified location.The location can be specified in the same form as writer.createPositionAt() parameters.
Parameters
itemOrPosition : Position | Item[ offset ] : PositionOffsetOffset or one of the flags. Used only when first parameter is a model item.
Returns
void
Fires
-
setTo( args ) → voidmodule:engine/model/selection~Selection#setToSets this selection's ranges and direction to the specified location based on the given selectable.
// Removes all selection's ranges. selection.setTo( null ); // Sets selection to the given range. const range = writer.createRange( start, end ); selection.setTo( range ); // Sets selection to given ranges. const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ]; selection.setTo( ranges ); // Sets selection to other selection. // Note: It doesn't copy selection attributes. const otherSelection = writer.createSelection(); selection.setTo( otherSelection ); // Sets selection to the given document selection. // Note: It doesn't copy selection attributes. const documentSelection = new DocumentSelection( doc ); selection.setTo( documentSelection ); // Sets collapsed selection at the given position. const position = writer.createPositionFromPath( root, path ); selection.setTo( position ); // Sets collapsed selection at the position of the given node and an offset. selection.setTo( paragraph, offset );Creates a range inside an element which starts before the first child of
- that element and ends after the last child of that element.
selection.setTo( paragraph, 'in' );Creates a range on an item which starts before the item and ends just after the item.
selection.setTo( paragraph, 'on' );Selection#setTo()' method allow passing additional options (backward) as the last argument.// Sets backward selection. const selection = writer.createSelection( range, { backward: true } );Parameters
args : tuple
Returns
void
-
inherited
stopDelegating( [ event ], [ emitter ] ) → voidmodule:engine/model/selection~Selection#stopDelegatingStops delegating events. It can be used at different levels:
- To stop delegating all events.
- To stop delegating a specific event to all emitters.
- To stop delegating a specific event to a specific emitter.
Parameters
[ event ] : stringThe name of the event to stop delegating. If omitted, stops it all delegations.
[ emitter ] : Emitter(requires
event) The object to stop delegating a particular event to. If omitted, stops delegation ofeventto all emitters.
Returns
void
-
inherited
stopListening( [ emitter ], [ event ], [ callback ] ) → voidmodule:engine/model/selection~Selection#stopListening:BASE_STOPStops listening for events. It can be used at different levels:
- To stop listening to a specific callback.
- To stop listening to a specific event.
- To stop listening to all events fired by a specific object.
- To stop listening to all events fired by all objects.
Parameters
[ emitter ] : EmitterThe object to stop listening to. If omitted, stops it for all objects.
[ event ] : string(Requires the
emitter) The name of the event to stop listening to. If omitted, stops it for all events fromemitter.[ callback ] : Function(Requires the
event) The function to be removed from the call list for the givenevent.
Returns
void
-
Checks if given range intersects with ranges that are already in the selection. Throws an error if it does.
Parameters
range : Range
Returns
void
-
-
Adds given range to internal ranges array. Throws an error if given range is intersecting with any range that is already stored in this selection.
Parameters
range : Range
Returns
void
-
Deletes ranges from internal range array. Uses _popRange to ensure proper ranges removal.
Returns
void
-
protected
_replaceAllRanges( ranges ) → voidmodule:engine/model/selection~Selection#_replaceAllRangesReplaces all the ranges by the given ones. Uses _popRange and _pushRange to ensure proper ranges removal and addition.
Parameters
ranges : Array<Range>
Returns
void
-
protected
_setRanges( newRanges, isLastBackward ) → voidmodule:engine/model/selection~Selection#_setRangesReplaces all ranges that were added to the selection with given array of ranges. Last range of the array is treated like the last added range and is used to set
anchorandfocus. Accepts a flag describing in which direction the selection is made.Parameters
newRanges : Iterable<Range>Ranges to set.
isLastBackward : booleanFlag describing if last added range was selected forward - from start to end (
false) or backward - from end to start (true).Defaults to
false
Returns
void
Fires
Events
-
change:attribute( eventInfo, directChange = { directChange.attributeKeys, directChange.directChange } )module:engine/model/selection~Selection#event:change:attributeFired when selection attribute changed.
Parameters
eventInfo : EventInfoAn object containing information about the fired event.
directChange : objectIn case of
Selectionclass it is always set totruewhich indicates that the selection change was caused by a direct use of selection's API. TheDocumentSelection, however, may change because its attributes were directly changed through the writer or because its position was changed in the model and its attributes were refreshed (which means an indirect change). The indirect change does not occur in case of normal (detached) selections because they are "static" (as "not live") which mean that they are not updated once the document changes.PropertiesdirectChange.attributeKeys : Array<string>directChange.directChange : boolean
-
change:range( eventInfo, directChange = { directChange.directChange } )module:engine/model/selection~Selection#event:change:rangeFired when selection range(s) changed.
Parameters
eventInfo : EventInfoAn object containing information about the fired event.
directChange : objectIn case of
Selectionclass it is always set totruewhich indicates that the selection change was caused by a direct use of selection's API. TheDocumentSelection, however, may change because its position was directly changed through the writer or because its position was changed because the structure of the model has been changed (which means an indirect change). The indirect change does not occur in case of normal (detached) selections because they are "static" (as "not live") which mean that they are not updated once the document changes.PropertiesdirectChange.directChange : boolean
Every day, we work hard to keep our documentation complete. Have you spotted outdated information? Is something missing? Please report it via our issue tracker.
With the release of version 42.0.0, we have rewritten much of our documentation to reflect the new import paths and features. We appreciate your feedback to help us ensure its accuracy and completeness.