-3

In CSS, in order to change the highlight color, you add the following:

element::selection { color: red; }

How can you set the ::selection css attribute in JavaScript?

Mystical
  • 2,066
  • 2
  • 20
  • 35

1 Answers1

3

You could create a style element and place it in the head with the appropriate CSS that you need. A variation on: https://stackoverflow.com/a/524721/23528

var css = 'element::selection { color: red; }',
    head = document.head || document.getElementsByTagName('head')[0],
    style = document.createElement('style');

style.type = 'text/css';
if (style.styleSheet){
  // This is required for IE8 and below.
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}

head.appendChild(style);
Daniel A. White
  • 181,601
  • 45
  • 354
  • 430