JSFiddle - React, Tailwind, and code Playground
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);
}