I have a feature to change the color of selected text using Javascript. Here is the method I am currently using:
function marking_text(replacrmenthtml){
try {
if (window.getSelection) {
sel = window.getSelection();
var range = sel.getRangeAt(0);
var selectionStart = $("<span style=\"color:red\">");
var startRange = document.createRange();
startRange.setStart(range.startContainer, range.startOffset);
var selectionEnd = $("</span>");
var endRange = document.createRange();
endRange.setStart(range.endContainer, range.endOffset);
startRange.insertNode(selectionStart[0]);
endRange.insertNode(selectionEnd[0]);
}
}
catch (e) {
}
}
However, when calling this method, it encounters a DOM exception. It seems that inserting the starting span tag before the selected text causes disruption in the DOM structure without an end tag present. How can this issue be resolved?
Edited: There will be a highlight button. When the user selects text and clicks on the highlight button, the color of the selected text will change.