Get all css root variables in array using javascript and change the values

Nadeem Mohammed picture Nadeem Mohammed · Feb 13, 2018 · Viewed 7.7k times · Source

I am using css root variables in my project for dynamically changing the colors of all elements anytime.

My css looks like

:root{
  --primaryColor:aliceblue;
  --secondaryColor:blue;
  --errorColor:#cc2511;
}

used in css

.contentCss {
  background-color: var(--primaryColor);
} 

I can access variable in javascript as follows to change value dynamically

document.documentElement.style.setProperty('--primaryColor', 'green');

It works fine. I want to get all variables inside an array and according to that change the values of each variable dynamically.

Answer

tnt-rox picture tnt-rox · Feb 24, 2019

this script will return an array of root variables in all stylesheets, served from the domain. Out of domain stylesheets are not accessible due to CORS policies.

Array.from(document.styleSheets)
  .filter(
    sheet =>
      sheet.href === null || sheet.href.startsWith(window.location.origin)
  )
  .reduce(
    (acc, sheet) =>
      (acc = [
        ...acc,
        ...Array.from(sheet.cssRules).reduce(
          (def, rule) =>
            (def =
              rule.selectorText === ":root"
                ? [
                    ...def,
                    ...Array.from(rule.style).filter(name =>
                      name.startsWith("--")
                    )
                  ]
                : def),
          []
        )
      ]),
    []
  );

Note: a root: rule in a lower order stylesheet will override a parent root rule.