Changing CSS from JavaScript

I’m trying to make a “number chart” from 1 to 100 image … and say “highlight every nth number” … I’ve figured out how to do that in css:

section  > div:nth-child(4n)
/* section > div: var(--multiplier) */

… that will highlight every fourth div on my grid.
I want to be able to change this to 5n, 2n, etc. (tho’ if it’s too weird, I don’tneed to…)

I tried making a variable in the CSS … didn’t work.

Is there a way to add stuff to a style sheet from JavaScript? I found some examples online but they were changing simpler styles and it didn’t work. (I could change the highlighting color… but not the ‘4n’ part.) is the actual entity…

You could create a function with one parameter (n) that you could call to change the background color just like you are doing with the CSS. You could use the querySelectorAll method and dynamically create a CSS selector string to be used as the querySelectorAll’s argument. Then, you would iterate through that returned nodeList and change the background property of each element in the nodeList.

1 Like

You could modify your existing createMultImage function to be:

function createMultImage(n) {
  changeBackgrounds('section > div', 'palevioletred');
  changeBackgrounds('section > div:nth-child(' + n + 'n)', 'yellow');

Add a new function:

function changeBackgrounds(selectorStr, bgColor) {
  document.querySelectorAll(selectorStr).forEach(elem => { = bgColor;

Then, in the last line line of the newFact function’s else statement code block change:




This is challenging :wink: I went back to have the number divs added in a loop rather than 100 divs (successfully and quickly, to my delight)… but can’t figure out what the changeBackgrounds function means. (Looking for “elem” got me information about … hoisting…) I tried to just get any style to change and failed.

(and I forked it… the new is at )

function changeBackgrounds(selectorStr, bgColor) {
let newColor=bgColor;
  // document.querySelectorAll(selectorStr).forEach(elem => {
  // = bgColor;
  // });   

… okay, the “if you ask for help things will work” has worked and I successfully added .style. and got that to happen :wink: I’m back to it…(no, that’s nto the change I want to happen but … I am trying to figure out what’s going on without the complication of there being lots of elements… )