JSFiddle - React, Tailwind, and code Playground

HTML

<p>rofl im helicopted</p>

CSS

span {
    color:red
}

a {
    color:red
}

span:before{
    width:100px;
    height:20px;
    position:absolute;
    content: " som before ";
    background-color:silver;
    margin-top:30px
}

JavaScript

// nevím jak jsi zvyklí formátovat kód, ale to byla hrůza, jak JavaScript, tak CSS.

function doit(e) {
    var x = window.getSelection();
    var range = x.getRangeAt(0);
    var g = document.createElement("span");
    range.surroundContents(g);
    
    // kouzlo, resp. řešení problému, znovu vybereš obsah toho elementu
    window.getSelection().selectAllChildren(g);
}

window.onmouseup = doit;