JSFiddle - React, Tailwind, and code Playground

by Edison Xu

HTML

<p>
   Hello my name is jimmy john. Nice name. I hate sandwiches. 
<p>

CSS

span {color: green;}

JavaScript

function getSelectedText() {
  t = (document.all) ? document.selection.createRange().text : document.getSelection();

  return t;
}

$('body').mouseup(function(){
    var selection = getSelectedText();
    var selection_text = selection.toString();
    
    // How do I add a span around the selected text?
    
    var span = document.createElement('SPAN');
    span.textContent = selection_text;
    
    var range = selection.getRangeAt(0);
    range.deleteContents();
    range.insertNode(span);
});