JSFiddle - React, Tailwind, and code Playground

by Palpatim

HTML

<div contenteditable="true"><span class="mark">Firstword</span> Secondword Thirdword</div>

<button id="getSelectionButton">Get Selection</button>

CSS

div {
    height: 200px;
    width: 200px;
    border: 1px solid black;
}

.mark {
    background: #fcc;
}

JavaScript

function getSelection() {
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        console.log('sel::', sel);
        if (sel.rangeCount) {
            range = sel.getRangeAt(0).cloneRange();
            return range.startOffset;
        }
    }
}


var b = document.getElementById('getSelectionButton');
    
b.addEventListener('click', function() {alert(getSelection());});