0

The following code work nicely, but only once. I've copied it twice to change the color again. But the word remains unresponsive. Is there any non-jQuery solution for the issue?

function red() {
  var selection = window.getSelection().getRangeAt(0);
  if (window.getSelection().baseNode.parentNode.id != "foo") return;
  var selectedText = selection.extractContents();
  var span = document.createElement("span");
  span.style.color = "red";
  span.appendChild(selectedText);
  selection.insertNode(span);
}

function blue() {
  var selection = window.getSelection().getRangeAt(0);
  if (window.getSelection().baseNode.parentNode.id != "foo") return;
  var selectedText = selection.extractContents();
  var span = document.createElement("span");
  span.style.color = "blue";
  span.appendChild(selectedText);
  selection.insertNode(span);
}
<button onclick="red()">Click to make highlighted text red.</button>
<button onclick="blue()">Click to make highlighted text blue.</button>
<div id="foo" style="width:30em; height:30em; border-style:solid; border-color:black;" contenteditable="true"></div>

Reference
Fiddle

j08691
  • 204,283
  • 31
  • 260
  • 272
Blue Line
  • 71
  • 1
  • 1
  • 5
  • 1
    You should ideally put the script at the bottom of the body tags. For example; `...` – Tyler2P Jan 05 '21 at 19:56
  • `if (window.getSelection().baseNode.parentNode.id != "foo") return;` is returning early if you have selected text that has already been changed, because its parent is no longer `#foo` but instead the `span` that was inserted. You can see this more clearly if you change that line to `if (window.getSelection().baseNode.parentNode.id != "foo") { console.log('parent is not foo'); return; }`. So the solution is to probably iterate over the selected characters, remove any parent `span` first, then run the rest of the `red()` function. – WOUNDEDStevenJones Jan 05 '21 at 20:49

0 Answers0