Skip to content

Instantly share code, notes, and snippets.

@enpitsuLin
Last active April 26, 2023 01:30
Show Gist options
  • Select an option

  • Save enpitsuLin/cb6da7effd495322a82b411e687286e2 to your computer and use it in GitHub Desktop.

Select an option

Save enpitsuLin/cb6da7effd495322a82b411e687286e2 to your computer and use it in GitHub Desktop.
get all css variable from :root
/*
const list = Array.from(document.styleSheets)
.filter((sheet) => sheet.href === null || sheet.href.startsWith(window.location.origin))
.reduce(
(acc, sheet) => [ //lower performance for this way
...acc,
...Array.from(sheet.cssRules).reduce(
(def, rule) =>
(def =
rule.selectorText === ':root'
? [...def, ...Array.from(rule.style).filter((name) => name.startsWith('--'))]
: def),
[]
)
],
[]
);
*/
const list = Array.from(document.styleSheets)
.filter((sheet) => sheet.href === null || sheet.href.startsWith(window.location.origin))
.reduce(
(acc, sheet) => acc.concat(Array.from(sheet.cssRules).reduce(
(def, rule) => {
if (rule.selectorText === ':root')
return def.concat(Array.from(rule.style).filter((name) => name.startsWith('--')))
return def
},
[]
)),
[]
);
const style = getComputedStyle(document.body);
list.reduce((map, cur) => {
return { ...map, [cur]: style.getPropertyValue(cur) };
}, {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment