Get all CSS variables on an HTML element with JavaScript when you don't know the names of the CSS Variables?

80 Views Asked by At

In JavaScript I need to read all the CSS vars that have been applied to an HTML element.

If I know the name of a CSS variable eg --thing I can get it's value with this code. This works in both Chrome and Firefox.

  const elem = document.querySelector("html");
  if (!elem) return;
  const style = getComputedStyle(elem);
  const myVariable = style.getPropertyValue("--thing");
  console.log({ myVariable });

I've tried iterating over the properties and looking for names that start with --. It works in Firefox but not in Chrome.

  for (let i = 0; i < style.length; i++) {
    const propertyName = style[i];
    if (propertyName.startsWith("--")) {
      console.log(propertyName);
    }
  }

Is there a solution that works cross browser or at least in Chrome?

UPDATE. Im not able to post an answer but this works in Firefox and Chrome (might not be the best solution)

  const res: Record<string, string> = {};

  if ("computedStyleMap" in elem) {
    // Chrome
    const styles = elem.computedStyleMap();
    Array.from(styles).forEach(([prop, val]) => {
      if (prop.startsWith("--")) {
        res[prop] = val.toString();
      }
    });
  } else {
    // Firefox
    const styles = getComputedStyle(elem);
    for (let i = 0; i < styles.length; i++) {
      const propertyName = styles[i];
      if (propertyName.startsWith("--")) {
        const value = styles.getPropertyValue(propertyName);
        res[propertyName] = value;
      }
    }
  }

  console.log({ res });
0

There are 0 best solutions below