Is there a way in JavaScript to dynamically remove text highlights that were applied using the execCommand("HiliteColor") method? I want to check if the selected text is within a highlighted span and then remove the highlight. Additionally, how can I handle situations where only part of the selected text is highlighted? I've attempted to manually add spans and remove highlights using the following code:
document.getElementsByClassName('highlight').remove();
alert(window.getComputedStyle(document.getElementById("pages"), null).getPropertyValue('background-color'));
alert(document.getElementById("pages").style.backgroundColor);
I tried checking the background color and removing the class 'highlight' but haven't had success yet.
You can view my project on CodePen at: https://codepen.io/pokepimp007/pen/wxGKEQ
SOLUTION
I have created a function that accepts a color parameter when a button is clicked. Clicking the "Delete Highlight" button sends the color parameter as "transparent":
function Highlight(color) {
document.designMode = "on';
var sel = window.getSelection();
sel.removeAllRanges();
var range = document.createRange();
range.setStart(editor.startContainer, editor.startOffset);
range.setEnd(editor.endContainer, editor.endOffset);
sel.addRange(range);
if (!sel.isCollapsed) {
if (!document.execCommand("HiliteColor", false, color)) {
document.execCommand("BackColor", false, color);
}
}
sel.removeAllRanges();
document.designMode = "off";
}