How to add a tag to a selected text and close/open the parent before/after

trying to create a Richt Texteditor in Javascript. I have a Tag

<span class="text-3xl">Foo</span>

and want to edit it to something like

<span class="text-3xl">F</span><span class="text-sm">o</span><span class="text-3xl">o</span>

My first attempt works, for inserting a Tag inside the other

<span class="text-3xl">F<span class="text-sm">o</span>o</span>

using this code:

  var spanElement= document.createElement("span");
  spanElement.className = size;
  var selection= window.getSelection().getRangeAt(0);
  var selectedText = selection.extractContents();
  elem.appendChild(selectedText);
  selection.insertNode(elem);


but need some help with closing/reopening the tag before/after the inner tag.