JSFiddle - React, Tailwind, and code Playground

by gooner12

HTML

<body>
  <p>
    Select a text and press the button to see the changes.
  </p>
  <button onclick="textInserter(true)">
    Insert Before Selection
  </button>
  <button onclick="textInserter(false)">
    Insert After Selection
  </button>
  <button onclick="textReplacer()">
    Replace the selection
  </button>
</body>

JavaScript

function textInserter(isBefore) {
  const selection = window.getSelection();
  const range = selection.getRangeAt(0);
  if (isBefore) {
    range.collapse(true);
  } else {
    range.collapse(false);
  }
  const textNode = document.createTextNode('"Text"');
  range.insertNode(textNode);
}

function textReplacer() {
  const selection = window.getSelection();
  const range = selection.getRangeAt(0);
  range.extractContents(); // removing the selected text from selection
  const textNode = document.createTextNode('"Replacing Text"');
  range.insertNode(textNode);
}