I highlighted selected text using JavaScript with the following code:
var sel = window.getSelection();
if(!sel.isCollapsed) {
var range = sel.getRangeAt(0);
sel.removeAllRanges();
document.designMode = "on";
sel.addRange(range);
document.execCommand("HiliteColor", false, "#ffffcc");
sel.removeAllRanges();
document.designMode = "off";
}
How do I then remove the highlighted color and restore the text?
Here's some code to add and remove highlights. It's too long to post here practically, so I've made a demo and posted a snippet below. It's not quite ideal because the unhighlight() function doesn't remove <span> elements inserted by the highlight command, but with a little care this would be a possible addition.
Live demo: http://jsfiddle.net/timdown/Bvd9d/
Code snippet:
function unhighlight(node, colour) {
if (!(colour instanceof Colour)) {
colour = new Colour(colour);
}
if (node.nodeType == 1) {
var bg = node.style.backgroundColor;
if (bg && colour.equals(new Colour(bg))) {
node.style.backgroundColor = "";
}
}
var child = node.firstChild;
while (child) {
unhighlight(child, colour);
child = child.nextSibling;
}
}
You could use CSS instead:
<style>
::selection {background-color: #ffffcc;}
</style>
EDIT: Update in response to comment and clarification
<script type="text/javascript">
var spans = document.getElementsByTagName('span'), i;
for( i=0; i<spans.length; i++) {
if( spans[i].style.backgroundColor == "#ffffcc") {
// Two alternatives. This:
spans[i].style.backgroundColor = "transparent";
// OR this, if spans contain only text:
spans[i].parentNode.replaceChild(spans[i].firstChild,spans[i]);
i--;
// End alternatives - only include i-- in the second one
}
}
</script>
Although, this fails in some browsers (I think it's Firefox) where the element style is changed to the computed style.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With