1

According to this answer, web selection background colors are dependent on the operating system/browser combination. I would like to change the foreground color of ::selection, but not the background; however, it seems that changing the former causes the latter to become invisible.

//https://stackoverflow.com/questions/985272/selecting-text-in-an-element-akin-to-highlighting-with-your-mouse
function selectText(node) {
  node = document.getElementById(node);

  if (document.body.createTextRange) {
    const range = document.body.createTextRange();
    range.moveToElementText(node);
    range.select();
  } else if (window.getSelection) {
    const selection = window.getSelection();
    const range = document.createRange();
    range.selectNodeContents(node);
    selection.removeAllRanges();
    selection.addRange(range);
  }
}
#changed::selection {
  color: red;
}

button,
p {
  display: inline;
}
<button onclick="selectText('normal')">Select</button>&nbsp;
<p id="normal">This text maintains the standard highlight color, which I want to maintain.</p>
<br>
<button onclick="selectText('changed')">Select</button>&nbsp;
<p id="changed">When I try to change the foreground color of the selection, the background color is unset.</p>
Jordan Mann
  • 402
  • 6
  • 16

0 Answers0