JavaScript

JavaScript TutorialDatatypes in JavaScriptEvaluating JavaScriptFunctional JavaScriptJavaScript .postMessage() and MessageEventJavaScript AJAXJavaScript Anti-patternsJavaScript Arithmetic (Math)JavaScript ArraysJavaScript Arrow FunctionsJavaScript Async functions (async/await)JavaScript Async IteratorsJavaScript Automatic Semicolon Insertion - ASIJavaScript Battery Status APIJavaScript Behavioral Design PatternsJavaScript Binary DataJavaScript Bitwise operatorsJavaScript Bitwise Operators - Real World Examples (snippets)JavaScript BOM (Browser Object Model)JavaScript Built-in ConstantsJavaScript CallbacksJavaScript ClassesJavaScript CommentsJavaScript Comparison OperationsJavaScript ConditionsJavaScript ConsoleJavaScript Constructor functionsJavaScript Context (this)JavaScript CookiesJavaScript Creational Design PatternsJavaScript Custom ElementsJavaScript Data attributesJavaScript Data ManipulationJavaScript DateJavaScript Date ComparisonJavaScript DebuggingJavaScript Declarations and AssignmentsJavaScript Destructuring assignmentJavaScript Detecting browserJavaScript EnumerationsJavaScript Error HandlingJavaScript Escape SequencesJavaScript EventsJavaScript execCommand and contenteditableJavaScript FetchJavaScript File API, Blobs and FileReadersJavaScript Fluent APIJavaScript FunctionsJavaScript GeneratorsJavaScript GeolocationJavaScript Global error handling in browsersJavaScript HistoryJavaScript How to make iterator usable inside async callback functionJavaScript IndexedDBJavaScript InheritanceJavaScript Intervals and TimeoutsJavaScript JSONJavaScript Linters - Ensuring code qualityJavaScript LocalizationJavaScript LoopsJavaScript MapJavaScript Memory efficiencyJavaScript Method ChainingJavaScript Modals - PromptsJavaScript Modularization TechniquesJavaScript ModulesJavaScript NamespacingJavaScript Navigator ObjectJavaScript Notifications APIJavaScript ObjectsJavaScript Performance TipsJavaScript PromisesJavaScript Prototypes, objectsJavaScript ProxyJavaScript Regular expressionsJavaScript requestAnimationFrameJavaScript Reserved KeywordsJavaScript Same Origin Policy & Cross-Origin CommunicationJavaScript ScopeJavaScript ScreenJavaScript Security issuesJavaScript Selection APIJavaScript Server-sent eventsJavaScript SetJavaScript Setters and GettersJavaScript Strict modeJavaScript StringsJavaScript SymbolsJavaScript Tail Call OptimizationJavaScript Template Literals



JavaScript Selection API

From WikiOD

Syntax[edit | edit source]

  • 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[edit | edit source]

Parameter Details
startOffset If 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.
endOffset If 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.

Remarks[edit | edit source]

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.

Get the text of the selection[edit | edit source]

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());

Deselect everything that is selected[edit | edit source]

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

Select the contents of an element[edit | edit source]

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.

Credit:Stack_Overflow_Documentation