Table of Contents

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

About

A Selection represents:

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

<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>
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})`)

});

Glossary

Anchor/Focus

In a 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

.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>

Documentation / Reference