JSFiddle - React, Tailwind, and code Playground

HTML

<div>Select something in here, but only once</div>

CSS

span.highlightedText {
    color: red;
    font-weight: bold;
}

JavaScript

function myOnclikFunction() {
    alert("Span clicked");
}

function highlightText() {
    var selection = window.getSelection();
    if (selection.rangeCount > 0) {
        var range = selection.getRangeAt(0);
        var selectedText = range.toString();

        var span = document.createElement("span");
        span.id = "span_" + range.startOffset + "_" + range.endOffset;
        span.className = "highlightedText";
        span.onclick = function() {
            myOnclikFunction(selectedText);
        };

        range.surroundContents(span);
        
        // Restore selection
        selection.removeAllRanges();
        selection.addRange(range);
    }
}


document.onmouseup = highlightText;