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>