Currently, I am working on a contenteditable div feature (identified by id 'editor1') which allows users to input text. Additionally, there is a function that enables users to highlight and change the color of selected text. In my JavaScript code, I utilize
window.getSelection().getRangeAt(0)
, however, I have encountered an issue where users can select text outside of the div causing all highlighted words to change color. To address this problem, I have attempted the following:
function red(){
{
var getText = document.getElementById("editor1").innerHTML;
var selection = getText.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement("span");
span.style.color = "red";
span.appendChild(selectedText);
selection.insertNode(span);
}
}
You can view a live example here: https://jsfiddle.net/xacqzhvq/
Currently, if I were to highlight "this will become red as well," the button allows me to change the color as desired. However, my main concern remains - how can I limit the color-changing functionality to only affect text within the editor1 div?