JSFiddle - React, Tailwind, and code Playground

by Neeraj Yadav

HTML

<p>Lorem ipsum dolor sit</p>
<!-- <button onclick="highlight()">Highlight</button> -->

JavaScript

window.highlight = function() {
    var selection = window.getSelection().getRangeAt(0);
    var selectedText = selection.extractContents();
    var span = document.createElement("span");
    span.style.backgroundColor = "yellow";
    span.appendChild(selectedText);
    /* span.onclick = function (ev) {
        this.parentNode.insertBefore(document.createTextNode(this.innerHTML), this);
        this.parentNode.removeChild(this);
    } */
    selection.insertNode(span);
}

document.onmouseup = function(){highlight()}
if (!document.all) document.captureEvents(Event.MOUSEUP);