JSFiddle - React, Tailwind, and code Playground

HTML

<input type="button" onclick="surroundSelection()" value="Surround">
<div contenteditable="true">One two three four</div>

CSS

div, input {
  padding:10px; 
  
}

JavaScript

function surroundSelection() {
    var code = document.createElement("code");
    code.style.fontStyle = "italic";
    code.style.color = "#333";
    code.style.background = "#ddd";
    
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(code);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
}