Danjo_O Danjo_O - 11 days ago 6
CSS Question

Format string in an insertRule javascript statement

I am looking to change the :hover style of a nav element through Javascript using insertRule. The background color of the nav link will change based on bgndImgIndex. Is this possible with Javascript or am I just plain wrong?

var bgndImgIndex = 0;
var colorSelect = ['#ffa800', '#ba2a2a', '#5ad339'];

var sheet = document.styleSheets[0];

sheet.insertRule("a:hover {background:{0} !important".format(colorSelect[bgndImgIndex]), 4);

Answer

That's totally possible. It seems the issue was that .format does not exist on the String prototype in JS. I usually use ES6 template strings for this task in JS, please see the working example:

var bgndImgIndex = 0;
var colorSelect = ['#ffa800', '#ba2a2a', '#5ad339'];

var sheet = document.styleSheets[0];

sheet.insertRule(
  `a:hover {background:${colorSelect[bgndImgIndex]} !important`
);
<a>Test</a>