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 addPad() {
var $input = document.querySelector('div');
var pad = document.createTextNode('\u00A0');
$input.appendChild(pad);
return pad;
}
function surroundSelection() {
var sel = window.getSelection();
if (!sel || !sel.rangeCount) return;
var code = document.createElement("code");
code.style.fontStyle = "italic";
code.style.color = "#333";
code.style.background = "#ddd";
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(code);
sel.removeAllRanges();
sel.addRange(range);
var padNode = addPad();
range.setEnd(padNode, 1);
sel.collapseToEnd();
}