HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

How can I get the currently selected text in the browser?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptselectedhowgetthecancurrentlytextbrowser

Problem

When working with text in the browser, you may need to get the currently selected text to perform various operations. This can be useful for implementing features like copy-paste functionality, text highlighting, or custom context menus.
As usual, JavaScript provides a way to achieve this using Window.getSelection(), which returns a Selection object representing the text currently selected in the document. You can then use Selection.toString() to get the actual text content.
> [!NOTE]
>
> A more advanced use case of this functionality can be found in the copy text to clipboard article, used to select and copy text to the clipboard.

Solution

const getSelectedText = () => window.getSelection().toString();

getSelectedText(); // 'Lorem ipsum'


> [!NOTE]
>
> A more advanced use case of this functionality can be found in the copy text to clipboard article, used to select and copy text to the clipboard.

Code Snippets

const getSelectedText = () => window.getSelection().toString();

getSelectedText(); // 'Lorem ipsum'

Context

From 30-seconds-of-code: get-selected-text

Revisions (0)

No revisions yet.