I want to highlight feature which will change the color of the selected text using Javascript. I am using the following method.
function android_selection_highlight(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) {
}
}
But it is giving DOM exception when I am calling the method. I think that when I am inserting starting span tag in front of the selected text, it is disrupting the DOM structure as there is no end tag at that moment. How to solve this problem?
Edited: There will a highlight button. Selecting the text, if user click on the highlight button, the text color of the selected text will change.