Skip to content

Instantly share code, notes, and snippets.

@queviva
Last active February 4, 2022 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save queviva/69f775902fa0174e690af16315545fd8 to your computer and use it in GitHub Desktop.
Save queviva/69f775902fa0174e690af16315545fd8 to your computer and use it in GitHub Desktop.
create list of all css variables
// run after all styles load
const cssVars = {
list : () => [...new Set([...[
[...document.styleSheets]
.map(s => [...s.cssRules]
.map(r => r.cssText)),
[...document.querySelectorAll('[style]')]
.map(n => n.getAttribute('style'))]
.join(' ')
.matchAll(/(--[^:;]*):/gm)]
.map(a => a[1])
)],
obj: () => Object.fromEntries([...[
[...document.styleSheets]
.map(s => [...s.cssRules]
.map(r => r.cssText)),
[...document.querySelectorAll('[style]')]
.map(n => n.getAttribute('style'))]
.join(' ')
.matchAll(/(--[^:;]*):([^;]*);/gm)]
.map(a => [a[1],a[2]])
)
};
@queviva
Copy link
Author

queviva commented Feb 3, 2022

this will get really close to finding all css variable names; it looks in external styles and inline style parameters aswell

it has to be run either in a defer script, from a script tag after the body, or after window.onload - all the styles should be loaded before running this

cssVars.list() // returns array of all css variable names

cssVars.obj() // returns object of key:::value pairs

the cssVars.obj() version seems worthless to me; the value of the variable will simple be whatever is coded - if you want to know the actual current value being used by an element, you have to .getPropertyValue('--css-variable') anyway, so I don't know why people would be interested in that, except maybe to see matchAll() and the regex?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment