Getting started with JavaScriptFunctionsArraysObjectsAJAXClassesArithmetic (Math)Comparison OperationsConditionsLoopsPromisesRegular expressionsDateError HandlingGeolocationCookiesIntervals and TimeoutsGeneratorsHistoryStrict modeCustom ElementsJSONBinary DataTemplate LiteralsWeb StorageFetchScopeModulesScreenInheritanceTimestampsDestructuring assignmentWorkersVariable coercion/conversionDebuggingNotifications APIBuilt-in ConstantsWebSocketsWeb Cryptography APIAsync functions (async/await)StringsConstructor functionsexecCommand and contenteditablePerformance TipsMapCreational Design PatternsrequestAnimationFrameReserved KeywordsMethod ChainingGlobal error handling in browsersUnary OperatorsFile API, Blobs and FileReadersCommentsConsoleTail Call OptimizationDetecting browserEnumerationsSymbolsLocalizationSelection APICallbacksSetDeclarations and AssignmentsFunctional JavaScriptModals - PromptsData attributesThe Event LoopBattery Status APIData ManipulationBitwise operatorsTranspilingBOM (Browser Object Model)Unit Testing JavascriptLinters - Ensuring code qualityAutomatic Semicolon Insertion - ASIIndexedDBAnti-patternsNavigator ObjectModularization TechniquesProxySame Origin Policy & Cross-Origin CommunicationArrow Functions.postMessage() and MessageEventWeakMapWeakSetEscape SequencesBehavioral Design PatternsServer-sent eventsAsync IteratorsNamespacingEvaluating JavaScriptMemory efficiencyDate ComparisonHow to make iterator usable inside async callback functionContext (this)Setters and GettersVibration APIPrototypes, objectsDatatypes in JavascriptBitwise Operators - Real World Examples (snippets)Fluent APITilde ~Security issuesUsing javascript to get/set CSS custom variablesJavaScript VariablesEvents

Selection API

Other topics

Remarks:

The Selection API allows you to view and change the elements and text that are selected (highlighted) in the document.

It is implemented as a singleton Selection instance that applies to the document, and holds a collection of Range objects, each representing one contiguous selected area.

Practically speaking, no browser except Mozilla Firefox supports multiple ranges in selections, and this is not encouraged by the spec either. Additionally, most users are not familiar with the concept of multiple ranges. As such, a developer can usually only concern themselves with one range.

Deselect everything that is selected

let sel = document.getSelection();
sel.removeAllRanges();

Select the contents of an element

let sel = document.getSelection();

let myNode = document.getElementById('element-to-select');

let range = document.createRange();
range.selectNodeContents(myNode);

sel.addRange(range);

It may be necessary to first remove all the ranges of the previous selection, as most browsers don't support multiple ranges.

Get the text of the selection

let sel = document.getSelection();
let text = sel.toString();
console.log(text); // logs what the user selected

Alternatively, since the toString member function is called automatically by some functions when converting the object to a string, you don't always have to call it yourself.

console.log(document.getSelection());

Syntax:

  • Selection sel = window.getSelection();
  • Selection sel = document.getSelection(); // equivalent to the above
  • Range range = document.createRange();
  • range.setStart(startNode, startOffset);
  • range.setEnd(endNode, endOffset);

Parameters:

ParameterDetails
startOffsetIf the node is a Text node, it is the number of characters from the beginning of startNode to where the range begins. Otherwise, it is the number of child nodes between the beginning of startNode to where the range begins.
endOffsetIf the node is a Text node, it is the number of characters from the beginning of startNode to where the range ends. Otherwise, it is the number of child nodes between the beginning of startNode to where the range ends.

Contributors

Topic Id: 2790

Example Ids: 9410,9411,9412

This site is not affiliated with any of the contributors.