I'm trying to get a list of all active CSS variables on a root element. I've set a couple CSS variables in my code and would like to overwrite these variables with different values in certain cases.
Here is my CSS variable setup:
:root {
--simpleResponse-background-color: #000;
--simpleResponse-text-color: #fff;
--simpleResponse-text-font: 'Arial';
--simpleResponse-text-font-weight: 'none';
--simpleResponse-text-font-size: 10
}
.simpleResponse {
background-color: var(--simpleResponse-background-color);
}
.paragraph {
color: var(--simpleResponse-text-color);
font-family: var(--simpleResponse-text-font);
font-weight: var(--simpleResponse-text-font-weight);
font-size: var(--simpleResponse-text-font-size);
margin: 0;
}
I would like to overwrite these variables using document.documentElement.style.setProperty('--variableName', newValue);
, but without having to add a line for each variable.
Therefor, I'm looking for a way to retrieve all the set CSS variables from my page, so I can update each variable accordingly using a loop. I've tried using document.documentElement.style
and getComputedStyle(root)
, but none of these options return the variables that are set.
const root = document.querySelector(':root');
if (!root) {
throw new Error('Cannot find root.')
}
const cssProperties = getComputedStyle(root);
Is it possible to retrieve these values from the page?