JSFiddle - React, Tailwind, and code Playground

HTML

<div id="editable" contenteditable="true">Here is some editable content. Select some of it and press the button.</div>

<input type="button" onclick="highlight(); return false" value="Highlight" unselectable="on">

JavaScript

function getSelectedText() {
    var selectedText = "", sel;
    if (window.getSelection) {
        selectedText = "" + window.getSelection();
    } else if ( (sel = document.selection) && sel.type == "Text") {
        selectedText = sel.createRange().text;
    }
    return selectedText;
}

function highlight() {
    var sel, html = '<span style="background-color: yellow">'
         + getSelectedText() + "</span>";

    if ( (sel = document.selection) && sel.type != "Control") {
        sel.createRange().pasteHTML(html);
    } else {
        document.execCommand("InsertHTML", false, html);
    }
}