
- Javascript Basics Tutorial
- Javascript - Home
- JavaScript - Roadmap
- JavaScript - Overview
- JavaScript - Features
- JavaScript - Enabling
- JavaScript - Placement
- JavaScript - Syntax
- JavaScript - Hello World
- JavaScript - Console.log()
- JavaScript - Comments
- JavaScript - Variables
- JavaScript - let Statement
- JavaScript - Constants
- JavaScript - Data Types
- JavaScript - Type Conversions
- JavaScript - Strict Mode
- JavaScript - Reserved Keywords
- JavaScript Operators
- JavaScript - Operators
- JavaScript - Arithmetic Operators
- JavaScript - Comparison Operators
- JavaScript - Logical Operators
- JavaScript - Bitwise Operators
- JavaScript - Assignment Operators
- JavaScript - Conditional Operators
- JavaScript - typeof Operator
- JavaScript - Nullish Coalescing Operator
- JavaScript - Safe Assignment Operator
- JavaScript - Delete Operator
- JavaScript - Comma Operator
- JavaScript - Grouping Operator
- JavaScript - Yield Operator
- JavaScript - Spread Operator
- JavaScript - Exponentiation Operator
- JavaScript - Operator Precedence
- JavaScript Control Flow
- JavaScript - If...Else
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For...in
- Javascript - For...of
- JavaScript - Loop Control
- JavaScript - Break Statement
- JavaScript - Continue Statement
- JavaScript - Switch Case
- JavaScript - User Defined Iterators
- JavaScript Functions
- JavaScript - Functions
- JavaScript - Function Expressions
- JavaScript - Function Parameters
- JavaScript - Default Parameters
- JavaScript - Function() Constructor
- JavaScript - Function Hoisting
- JavaScript - Self-Invoking Functions
- JavaScript - Arrow Functions
- JavaScript - Function Invocation
- JavaScript - Function call()
- JavaScript - Function apply()
- JavaScript - Function bind()
- JavaScript - Closures
- JavaScript - Variable Scope
- JavaScript - Global Variables
- JavaScript - Smart Function Parameters
- JavaScript Objects
- JavaScript - Number
- JavaScript - Boolean
- JavaScript - Strings
- JavaScript - Arrays
- JavaScript - Date
- JavaScript - DataView
- JavaScript - Handler
- JavaScript - Math
- JavaScript - RegExp
- JavaScript - Symbol
- JavaScript - Sets
- JavaScript - WeakSet
- JavaScript - Maps
- JavaScript - WeakMap
- JavaScript - Iterables
- JavaScript - Reflect
- JavaScript - TypedArray
- JavaScript - Template Literals
- JavaScript - Tagged Templates
- Object Oriented JavaScript
- JavaScript - Objects
- JavaScript - Classes
- JavaScript - Object Properties
- JavaScript - Object Methods
- JavaScript - Static Methods
- JavaScript - Display Objects
- JavaScript - Object Accessors
- JavaScript - Object Constructors
- JavaScript - Native Prototypes
- JavaScript - ES5 Object Methods
- JavaScript - Encapsulation
- JavaScript - Inheritance
- JavaScript - Abstraction
- JavaScript - Polymorphism
- JavaScript - Destructuring
- JavaScript - Destructuring Assignment
- JavaScript - Object Destructuring
- JavaScript - Array Destructuring
- JavaScript - Nested Destructuring
- JavaScript - Optional Chaining
- JavaScript - Global Object
- JavaScript - Mixins
- JavaScript - Proxies
- JavaScript Versions
- JavaScript - History
- JavaScript - Versions
- JavaScript - ES5
- JavaScript - ES6
- ECMAScript 2016
- ECMAScript 2017
- ECMAScript 2018
- ECMAScript 2019
- ECMAScript 2020
- ECMAScript 2021
- ECMAScript 2022
- JavaScript Asynchronous
- JavaScript - Asynchronous
- JavaScript - Callback Functions
- JavaScript - Promises
- JavaScript - Async/Await
- JavaScript - Microtasks
- JavaScript - Promisification
- JavaScript - Promises Chaining
- JavaScript - Timing Events
- JavaScript - setTimeout()
- JavaScript - setInterval()
- JavaScript Cookies
- JavaScript - Cookies
- JavaScript - Cookie Attributes
- JavaScript - Deleting Cookies
- JavaScript Browser BOM
- JavaScript - Browser Object Model
- JavaScript - Window Object
- JavaScript - Document Object
- JavaScript - Screen Object
- JavaScript - History Object
- JavaScript - Navigator Object
- JavaScript - Location Object
- JavaScript - Console Object
- JavaScript Web APIs
- JavaScript - Web API
- JavaScript - History API
- JavaScript - Storage API
- JavaScript - Forms API
- JavaScript - Worker API
- JavaScript - Fetch API
- JavaScript - Geolocation API
- JavaScript Events
- JavaScript - Events
- JavaScript - DOM Events
- JavaScript - addEventListener()
- JavaScript - Mouse Events
- JavaScript - Keyboard Events
- JavaScript - Form Events
- JavaScript - Window/Document Events
- JavaScript - Event Delegation
- JavaScript - Event Bubbling
- JavaScript - Event Capturing
- JavaScript - Custom Events
- JavaScript Error Handling
- JavaScript - Error Handling
- JavaScript - try...catch
- JavaScript - Debugging
- JavaScript - Custom Errors
- JavaScript - Extending Errors
- JavaScript Important Keywords
- JavaScript - this Keyword
- JavaScript - void Keyword
- JavaScript - new Keyword
- JavaScript - var Keyword
- JavaScript HTML DOM
- JavaScript - HTML DOM
- JavaScript - DOM Methods & Properties
- JavaScript - DOM Document
- JavaScript - DOM Elements
- JavaScript - DOM Attributes (Attr)
- JavaScript - DOM Forms
- JavaScript - Changing HTML
- JavaScript - Changing CSS
- JavaScript - DOM Animation
- JavaScript - DOM Navigation
- JavaScript - DOM Collections
- JavaScript - DOM NodeList
- JavaScript - DOM DOMTokenList
- JavaScript Advanced Chapters
- JavaScript - Bubble Sort Algorithm
- JavaScript - Circular Reference Error
- JavaScript - Code Testing with Jest
- JavaScript - CORS Handling
- JavaScript - Data Analysis
- JavaScript - Dead Zone
- JavaScript - Design Patterns
- JavaScript - Engine and Runtime
- JavaScript - Execution Context
- JavaScript - Function Composition
- JavaScript - Immutability
- JavaScript - Kaboom.js
- JavaScript - Lexical Scope
- JavaScript - Local Storage
- JavaScript - Memoization
- JavaScript - Minifying JS
- JavaScript - Mutability vs Immutability
- JavaScript - Package Manager
- JavaScript - Parse S-Expressions
- JavaScript - Prototypal Inheritance
- JavaScript - Reactivity
- JavaScript - Require Function
- JavaScript - Selection API
- JavaScript - Session Storage
- JavaScript - SQL CRUD Operations
- JavaScript - Supercharged Sorts
- JavaScript - Temporal Dead Zone
- JavaScript - Throttling
- JavaScript - TRPC Library
- JavaScript - Truthy and Falsy Values
- JavaScript - Upload Files
- JavaScript - Date Comparison
- JavaScript - Recursion
- JavaScript - Data Structures
- JavaScript - Base64 Encoding
- JavaScript - Callback Function
- JavaScript - Current Date/Time
- JavaScript - Date Validation
- JavaScript - Filter Method
- JavaScript - Generating Colors
- JavaScript - HTTP Requests
- JavaScript - Insertion Sort
- JavaScript - Lazy Loading
- JavaScript - Linked List
- JavaScript - Nested Loop
- JavaScript - Null Checking
- JavaScript - Get Current URL
- JavaScript - Graph Algorithms
- JavaScript - Higher Order Functions
- JavaScript - Empty String Check
- JavaScript - Form Handling
- JavaScript - Functional Programming
- JavaScript - Parameters vs Arguments
- JavaScript - Prototype
- JavaScript - Reactive Programming
- JavaScript - Reduce Method
- JavaScript - Rest Operator
- JavaScript - Short Circuiting
- JavaScript - Undefined Check
- JavaScript - Unit Testing
- JavaScript - Validate URL
- JavaScript Miscellaneous
- JavaScript - Ajax
- JavaScript - Async Iteration
- JavaScript - Atomics Objects
- JavaScript - Rest Parameter
- JavaScript - Page Redirect
- JavaScript - Dialog Boxes
- JavaScript - Page Printing
- JavaScript - Validations
- JavaScript - Animation
- JavaScript - Multimedia
- JavaScript - Image Map
- JavaScript - Browsers
- JavaScript - JSON
- JavaScript - Multiline Strings
- JavaScript - Date Formats
- JavaScript - Get Date Methods
- JavaScript - Set Date Methods
- JavaScript - Modules
- JavaScript - Dynamic Imports
- JavaScript - BigInt
- JavaScript - Blob
- JavaScript - Unicode
- JavaScript - Shallow Copy
- JavaScript - Call Stack
- JavaScript - Reference Type
- JavaScript - IndexedDB
- JavaScript - Clickjacking Attack
- JavaScript - Currying
- JavaScript - Graphics
- JavaScript - Canvas
- JavaScript - Debouncing
- JavaScript - Performance
- JavaScript - Style Guide
JavaScript - Selection API
JavaScript Selection API allows us to access and change or modify the portion of a web page which is selected by the user.This includes selecting which text or elements to highlight and providing options for connecting with the selected item. But it should be noticed that the Selection API is not available in Web Workers so it can only be used in a web-page's main thread.
The JavaScript Selection API provides a variety of essential APIs that allow developers to access and modify certain portions of a document. These interfaces contain the Selection and Range objects, as well as a number of helpful events that occur all over the selection process.
Selection Interface
A Selection object shows the user-selected region of text or the cursor's current position. Each document is given a unique selection object, which can be retrieved via document.getSelection(), or Window.getSelection() can then be examined and modified.
A user can choose between left to right and right to left. The anchor is where the user began the selection, whereas the focus is where the user ends it. When you make a selection with a desktop mouse, the anchor is set where you pressed the mouse button and the focus is placed where you let go.
Instance Properties
Here is the table provided of instance properties you can use for you reference −
Property | Description |
---|---|
Selection.anchorNode | This shows the part of the document where the selection starts. It will be empty if nothing was selected. |
Selection.anchorOffset | This tells how far the starting point of the selection is from the beginning. If the selection starts in a piece of text, it shows the number of characters before it. If it starts in an element (like a paragraph or list), it shows the number of other elements before it. |
Selection.direction | This shows if the selection was made from left to right, or right to left. |
Selection.focusNode | This shows the part of the document where the selection ends. It can also be empty if nothing was selected. |
Selection.focusOffset | Similar to anchorOffset, this shows how far the ending point of the selection is from the beginning in the focusNode. |
Selection.isCollapsed | This is true if the selection has no length (meaning the start and end are the same point), and false if there is a range of selected text. |
Selection.rangeCount | This tells you how many separate selections are made. |
Selection.type | This gives the type of selection. It can be "None" (no selection), "Caret" (a single point), or "Range" (a highlighted area). |
Instance Methods
Here is the table below in which we have provided the list of instance methods of Selection Interface with its description.
Methods | Content |
---|---|
Selection.addRange() | A Range object that will be added to the selection. |
Selection.collapse() | Collapses the current selection to a single point. |
Selection.collapseToEnd() | Collapses the selection to the end of the last range in the selection. |
Selection.collapseToStart() | Collapses the selection to the start of the first range in the selection. |
Selection.containsNode() | Indicates if a certain node is part of the selection. |
Selection.deleteFromDocument() | Deletes the selection's content from the document. |
Selection.empty() | Removes all ranges from the selection, leaving the anchorNode and focusNode properties equal to null and nothing selected. |
Selection.extend() | Moves the focus of the selection to a specified point. |
Selection.getComposedRanges() Experimental | Returns an array of StaticRange objects, each that represents a selection that might cross shadow DOM boundaries. |
Selection.getRangeAt() | Returns a Range object representing one of the ranges currently selected. |
Selection.modify() | Changes the current selection. |
Selection.removeRange() | Removes a range from the selection. |
Selection.removeAllRanges() | Removes all ranges from the selection. |
Selection.selectAllChildren() | Adds all the children of the specified node to the selection. |
Selection.setBaseAndExtent() | Sets the selection to be a range including all or parts of two specified DOM nodes, and any content located between them. |
Selection.setPosition() | Collapses the current selection to a single point. |
Selection.toString() | Returns a string currently being represented by the selection object, i.e., the currently selected text. |
Document.getSelection()
The getSelection() method of the Document interface returns the Selection object for this document which represents the user-selected text range or the caret's current position. And it acts like the window.getSelection().
Syntax
Below is the syntax of the Document.getSelection() −
document.getSelection()
Parameters
This method works without the need for any parameters.
Return value
This method basically returns a Selection object, or null if there is no browsing context (e.g., unattached <iframe>).
Example
Following is the example for showing the usage of Document.getSelection() object −
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document.getSelection Example</title> </head> <body> <p>Select some text in this paragraph and check the console.</p> <button onclick="getSelectedText()">Get Selected Text</button> <script> function getSelectedText() { let selection = document.getSelection(); if (selection.rangeCount > 0) { document.write("Selected text: " + selection.toString()); } else { document.write("No text selected."); } } </script> </body> </html>
Output
To view the messages use the browser's developer tools (usually by pressing F12) and select the "Console" tab.
Check the below message on the console after running the above code in browser −
Selected text: paragraph and check
Window.getSelection()
The getSelection() method of the Window interface returns the Selection object connected with the window's document which represents the range of text selected by the user or the caret's current position.
Syntax
Below is the syntax of the Window.getSelection() −
window.getSelection()
Parameters
This method does not require any parameters.
Return value
This method returns a Selection object or null if the connected document has browsing context (e.g. if the window is an unattached <iframe>).
Firefox gives null when a <iframe> is not displayed (e.g., display: none), whereas other browsers provide a Selection object with Selection.type set to None.
Example
Here is the example for showing the usage of Window.getSelection() object −
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Window.getSelection Example</title> </head> <body> <p>Select some text in this paragraph and check the console.</p> <button onclick="getSelectedText()">Get Selected Text</button> <script> function getSelectedText() { let selection = window.getSelection(); if (selection.rangeCount > 0) { document.write("Selected text: " + selection.toString()); } else { document.write("No text selected."); } } </script> </body> </html>
Output
So when to run the above HTML code in your browser. There will be a text will be appear with a button "Get Selected Text". So when you select some text and press the button then after inspecting the element you can see the below message on the console −
Selected text: this paragraph
Document: selectionchange event
The Selection API's selectionchange event is triggered when a Document's current Selection is changed. This event cannot be canceled and will not bubble.
The event can be handled by registering an event listener for selectionchange or by using the onselectionchange event handler.
Syntax
Use the event name in methods like addEventListener() or to set an event handler property.
addEventListener("selectionchange", (event) => {}); onselectionchange = (event) => {};
Event type
It is a generic Event.
Example
Here is the example of selectionchange event −
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Selection Change Example</title> </head> <body> <h1>Text Selection Example</h1> <p>Select some text in this paragraph to see the console messages about selection changes.</p> <p>Try selecting different parts of this text to see how it updates!</p> <script> // Using addEventListener to track selection changes document.addEventListener("selectionchange", () => { document.write("Selection has changed:", document.getSelection().toString()); }); // Using onselectionchange to handle selection changes document.onselectionchange = () => { document.write("Updated selection:", document.getSelection().toString()); }; </script> </body> </html>
Output
When you select any text in these paragraphs it will send messages to the console telling you that your selection has changed and displays the currently selected material.
[Log] Selection has changed: - "" (example.html, line 16) [Log] Updated selection: - "" (example.html, line 21) [Log] Selection has changed: - "" (example.html, line 16) [Log] Updated selection: - "" (example.html, line 21) [Log] Selection has changed: - "" (example.html, line 16) [Log] Updated selection: - "" (example.html, line 21) [Log] Selection has changed: - "Selection" (example.html, line 16) [Log] Updated selection: - "Selection" (example.html, line 21)
Node: selectstart event
This event occurs when the user starts making a new selection. For example, they can click and drag to highlight text. Suppose the event has been canceled so the selection is not changed.
Syntax
Use the event name in methods such as addEventListener() or set an event handler property.
addEventListener("selectstart", (event) => {}); onselectstart = (event) => {};
Event type
It is also a generic Event.
Example
Here is the example of selectstart event −
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Select Start Example</title> </head> <body> <h1>Text Selection Example</h1> <p>Choose some text in this paragraph to check the console messages.</p> <p>Try different parts of this text!</p> <script> // Using addEventListener to track when text selection starts document.addEventListener("selectstart", () => { document.write("Selection started"); }); // Using onselectstart to handle when text selection starts document.onselectstart = () => { document.write("Selection started."); }; </script> </body> </html>
Output
When you choose any text in these paragraphs, it will display "Selection started" and "Selection started." on the terminal.
[Log] Selection started (example.html, line 16) [Log] Selection started. (example.html, line 21) [Log] Selection started (example.html, line 16) [Log] Selection started. (example.html, line 21) [Log] Selection started (example.html, line 16) [Log] Selection started. (example.html, line 21) [Log] Selection started (example.html, line 16) [Log] Selection started. (example.html, line 21) [Log] Selection started (example.html, line 16) [Log] Selection started. (example.html, line 21)