The problem is likely that you're getting an exception parsing one of those prefixed rules, and so the code adding the others doesn't get run. If you put them in a try/catch, it works: (I also changed the tag name from html to *)
The following, for instance, works in Chrome, Firefox, and IE11:
var colors = ["#A3F8EF", "#FF7275", "#CBB6E7", "#FF9D74", "#FDF874"];
setRandomSelectionColor();
function setRandomSelectionColor() {
var n = Math.floor(Math.random() * colors.length);
var color = colors[n];
try {
document.styleSheets[0].insertRule("*::-moz-selection {background-color: " + color + ";}", 0);
}
catch (e) {
}
try {
document.styleSheets[0].insertRule("*::selection {background-color: " + color + ";}", 0);
}
catch (e) {
}
try {
document.styleSheets[0].insertRule("*::-webkit-selection {background-color: " + color + ";}", 0);
}
catch (e) {
}
}
<p>Select your text here!</p>
Original Answer (before I got curious why it was failing):
I didn't have any luck with insertRule, but you can dynamically create and replace a style element: (I also changed the tag name from html to *)
This works in Chrome, Firefox, and IE11:
var colors = ["#A3F8EF", "#FF7275", "#CBB6E7", "#FF9D74", "#FDF874"];
setRandomSelectionColor();
$("input").on("click", setRandomSelectionColor);
function setRandomSelectionColor() {
var n = Math.floor(Math.random() * colors.length);
var color = colors[n];
$("#the-style").remove();
$("<style id='the-style'>\n" +
"*::-moz-selection {background-color: " + color + ";}" +
"*::selection {background-color: " + color + ";}" +
"*::-webkit-selection {background-color: " + color + ";}" +
"</style>").appendTo('head');
}
<p>Select your text here!</p>
<input type="button" value="New Random Color">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>