JSFiddle - React, Tailwind, and code Playground

by Palpatim

HTML

<div id="editor" contenteditable="true"><span class="marked">Testing an <strong>inner</strong></span> Position of Preview</div>
<label for="selectionDisplay">Selection
    <textarea id="selectionDisplay"></textarea>
</label>
<button id="getSelection">Get Selection</button>

CSS

.marked {
    background: rgba(200, 255, 200, .3);
}
strong {
    background: rgba(200, 255, 255, .4);
}
div[contenteditable="true"] {
    width: 300px;
    height: 300px;
    border: 1px solid black;
    padding: 10px;
    margin: 10px 0;
}
label {
    display:block;
    margin: 10px 0;
}
#selectionDisplay {
    display: block;
    width: 300px;
    height: 200px;
    margin: 0;
    padding: 10px;
}

JavaScript

var editor = document.getElementById('editor');
var selButton = document.getElementById('getSelection');

function showSelection() {
    var msg;
    var sel = document.getSelection();
    var selectionDisplay = document.getElementById('selectionDisplay');
    console.log('sel ::', sel);
    if (!sel || !sel.baseNode) {
        msg = "No selection";
    } else {
        msg = 
            "sel.toString(): «" + sel.toString() + "»\n" +
            "anchorNode.data: " + sel.anchorNode.data + "\n" +
            "anchorOffset: " + sel.anchorOffset + "\n" +
            "anchorNode.parentElement: " + sel.anchorNode.parentElement + "\n" +
            "\n";
    }

    selectionDisplay.innerText = msg;
}

selButton.addEventListener('click', showSelection);
// editor.addEventListener('mouseup', showSelection);