I want to be able to select text click on a button and have the text color change e. The text color change should persist after the text is no longer selected.
I know that there are many solutions that do this already with CSS. However; I want to be able to have access to the nodes so that on another button click, I can revert the color change. I have tried looking into window.getSelection()
and Ranges
and DocumentFragment
, but I am having trouble understanding how to select the nodes in a DocumentFragment, modify each node, insert it in the right position in the document and also create a reference so that I can, in a later click, change the color again back to black.
I also found this thread which essentially does what I"m trying to do, but it uses execCommand which is obsolete.
I don't want a CSS solution and I don't want a solution that uses jQuery.
Below is the js code and codepen with a similar html structure that I am working with.
I have 2 buttons, one that changes the selections color and one that will revert the color of the selection even after the text is no longer selected.
I am using window.getSelection()
to get a Selection
of the selected text. I check that the Selection
is valid and then get a Range with getRangeAt(0)
followed by a call to extractContents()
.
This is where the hard part comes in because:
- It extracts the
DocumentFragment
from the document so how can I re-insert theDocumentFragment
in the same position it was extracted from? - I am having trouble figuring out how to modify the nodes in the
DocumentFragment
styles
var changeColorButton = document.getElementById('xyz');
var revertColor = document.getElementById('zyx');
const changeSelectionColor = () => {
let selection = window.getSelection()
if (selection) {
let range = selection.getRangeAt(0)
if (range) {
let frag = range.extractContents();
}
/*
2 problems:
1. accessing each node in the DocumentFragment and modifying the style then re-inserting into the correct spot
2. Creating a reference to this fragment for revertColorChange() to use to change the color back to black
*/
}
}
const revertColorChange = () => {
// revert color
}
changeColorButton.addEventListener('click', changeSelectionColor);
Minimal Reproducible Example - https://codepen.io/NoobCodePenner/pen/GRoKNRd