1213
1213

Reputation: 756

Get CSS variables applied to an element

In chrome / chromium, I would like to list all the CSS variables (variable names and values) applied on an HTML element. The following code works in Firefox but seams to be unsupported in webkit browsers. Is there a possible workaround?

let style = getComputedStyle(document.body);
for (let i = 0; i < style.length; i++) {
  let prop = style[i]
  if(prop.includes("--")){
    let val = style.getPropertyValue(prop)
    document.body.innerHTML = "Works in Firefox but not in Chromium:<br>"
    document.body.innerHTML += prop+" "+val
  }
}
:root{
  --c:lime;
}
body{
  background:var(--c);
}

Upvotes: 1

Views: 1176

Answers (1)

1213
1213

Reputation: 756

This solves the problem:

const isSameDomain = (styleSheet) => {
  if (!styleSheet.href) {
    return true;
  }

  return styleSheet.href.indexOf(window.location.origin) === 0;
};

const isStyleRule = (rule) => rule.type === 1;

const getCSSCustomPropIndex = () =>
  [...document.styleSheets].filter(isSameDomain).reduce(
    (finalArr, sheet) =>
      finalArr.concat(
        [...sheet.cssRules].filter(isStyleRule).reduce((propValArr, rule) => {
          const props = [...rule.style]
            .map((propName) => [
              propName.trim(),
              rule.style.getPropertyValue(propName).trim()
            ])
            .filter(([propName]) => propName.indexOf("--") === 0);

          return [...propValArr, ...props];
        }, [])
      ),
    []
  );

document.body.innerHTML = getCSSCustomPropIndex()
html {
  --c: lime;
}

 body {
  background:var(--c);
}

Thank you @evolutionxbox for pointing the solution.

Upvotes: 1

Related Questions