0

I'm trying to get the name of the variable used in CSS on an element

How can I return the string --my-background from document.getElementById("my_div")

getComputedStyle returns #000

:root {
  --my-background: #000;
}

.my_class {
  background-color: var(--my-background);
}
<div id="my_div" class="my_class">
  Test
</div>

I can't use the solution shown at How can I get css variable name(key) with javascript because multiple variables will have the same hex code

Mark
  • 70
  • 3
  • 13
  • Can't you guess from the returned values from [How can I get css variable name(key) with javascript](https://stackoverflow.com/questions/62655832/how-can-i-get-css-variable-namekey-with-javascript) – mplungjan Jan 13 '23 at 15:29
  • Unfortunately not. – Mark Jan 13 '23 at 15:44

1 Answers1

0

Not 100% sure what you are after actually

THIS is a closely related question: Can I detect if a specific CSS custom variable exists in the loaded styles?

Here as a verbose example of two different possible ways to get to what you are after; one on the entire document and one JUST on your element.

LOTS of comments and commented out parts here.

const declaration = document.styleSheets[0].cssRules[0].style;
//console.log(declaration);//huge list
const decValues = Object.values(declaration); // just values
//console.log("decValues:",decValues);
// just the ONE value we "know" starts with
//const foundVars = decValues.filter((v) => { return v.startsWith("--");});
//console.log("foundVars:",foundVars);// shows value for those (one) with it
let declarationC = Object.getOwnPropertyNames(declaration);
// console.log("declarationC:",declarationC); // just the property names
// the properties that start with "--"
const allNotEmptyComputedStyles = Object.fromEntries(
  Object.entries(declaration).filter(
    ([_, value]) => value.startsWith("--")
  )
);
// this is "0" key name because that is where it IS in the properties
console.log("allNotEmptyComputedStyles:", allNotEmptyComputedStyles);

/* now a different way just on the element */
let me = document.getElementById("my_div");
let cs = getComputedStyle(me);
// big list of all console.log("cs:",cs);
let cspv = cs.getPropertyValue('--my-background');
console.log("cspv:", cspv);
console.log("PV:", allNotEmptyComputedStyles["0"], cs.getPropertyValue(allNotEmptyComputedStyles["0"]));
:root {
  --my-background: #000;
}

.my_class {
  background-color: var(--my-background);
}
<div id="my_div" class="my_class">
  Test
</div>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100