Reputation: 929
Given
<div></div>
<style>
body {
--var1: 3;
--var2: var(--var1);
}
div {
--var3: var(--var2);
width: var(--var3);
}
</style>
How can I obtain the reference list of css variables?
getReferenceList(divElement, 'width')
Would result in
['--var3', '--var2', '--var1', 3]
Upvotes: 1
Views: 77
Reputation: 5439
If you already know the property name, you can use getComputedStyle. For instance,
window.getComputedStyle(document.querySelector('body')).getPropertyValue('--var1');
This will return 3
.
If you would like to get a list of all stylesheets, you can use CSSStyleSheet.cssRules.
The following example will give you the stylesheet of body
:
document.styleSheets[0].cssRules[0].cssText
So the result of it will be "body { --var1: 3; --var2: var(--var1); }"
.
In your case, cssRules[0]
= body
and cssRules[1]
= div
.
You can also use selectorText
to find out what tag it is. In this case document.styleSheets[0].cssRules[0].selectorText
will return the string body
.
If you prefer an array of properties and values, instead of a string, you can use this regex:
const regex = /(?<={)[ -a-zA-Z0-9\S][^}]+/gm
const str = document.styleSheets[0].cssRules[0].cssText.match(regex);
console.log(str[0].split(';'));
Upvotes: 2