How to select text dynamically in a Browser with Javascript? The window Selection Object explained

Browser

About

A Selection represents:

  • the text selected by the user, called a range selection
  • or the current position of the caret/cursor, called a caret selection

This article shows you how to manipulate the window.selection object of the webapi (browser) (made by a mouse, a keyboard, or a script) in a browser.

Example

Force the selection of a whole section

See What is the selectstart DOM event with examples and howto's in Javascript?

Playing with the Range of a selection

  • The text to select
<p id="p-1">
   <span id="span-1">
       The first part of a sentence
   </span> 
   is always 
   <span id="span-2">
       the most difficult part
   </span> 
</p>
  • The code that triggers on mouseup
document
.addEventListener('mouseup', () => {

    const nativeSelection = document.getSelection()
    const nativeRange = nativeSelection.rangeCount ? nativeSelection.getRangeAt(0) : undefined
    
    let selectedText = nativeSelection.toString();
    let collapsed = nativeRange.collapsed;
    let startOffset = nativeRange.startOffset;
    let endOffset = nativeRange.endOffset;
    let startParentId = nativeRange.startContainer.parentElement.id;
    let endParentId = nativeRange.endContainer.parentElement.id;

    console.log(`The selection is between ${startOffset} and ${endOffset} inside the containers ${startParentId} and ${endParentId}`)
    console.log(`The selected text is (${selectedText})`)

});
  • Result: Select the first letter T below, you will see that it does not start at 1 but at 8, this is because there is 8 spaces.

Glossary

Anchor/Focus

In a selection:

  • The anchor is where the user began the selection. It's called the anchor because this is the location that does not move during the selection.
  • The focus is where the user ends the selection.

Collapsed

A collapsed selection is a point meaning that the anchor and the focus are at the same location

Event

When a selection is taking place, the dom events (select, selectstart, selectend) are fired.

Note

CSS

This is a note to say that CSS has also the user-select property that have an effect on selection.

This example shows you how to apply the user-select css properties to re-do the behavior of the first example

  • The CSS
.select-all {
    user-select: all!important;
}
<section id="parent" class="select-all">
   <h1>You can select only the whole section</h1>
   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
</section>
  • Output: try to select only a word

Documentation / Reference





Discover More
Browser / DOM - Range - defining a sequence of characters

Range is a function that permits defining a sequence of characters in the DOM tree and is used in selecting and copying content.
Devtool Chrome Event Listener
DOM - Event Type (name)

An event is categorize by its type which is a property of the event object The type of an event is also known as the name of the event (Ref)...
Devtool Chrome Event Listener
Select Events (selectstart, selection change)

This page is the events that are fired when a selection of text occurs The select event occurs when a user selects some text in form controls when their text selection is adjusted (whether by an...
Devtool Chrome Event Listener
What is the selectstart DOM event with examples and howto's in Javascript?

selectstart is a selection event that occurs when the user agent (the browser used by the user mostly) is to associate a new range to a selection object Note that when the user clicks on: a text,...



Share this page:
Follow us:
Task Runner