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

2

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.