0

I have a wrapper like this (simple code):

<div class="wrapper" style="--main-color: #123456;">
...
</div>

I use the "--main-color" to change colors of different things (background, markers, etc.) a little bit easier or however to say. Works perfectly fine in css with this:

.classname {
  color: var(--main-color);
}

Now, what I want to with this too: I have 4 different images, but only one should be shown (depends on which color is specified)

E.G.

#ff0000 --> <img.... src(red-img.png).../>
#00ff00 --> <img.... src(green-img.png).../>

I am trying it already with javascript, but I absolutely dont know how to get the value of my attribute "--main-color".

One thing i tried, that ofc didnt work:

let color = document.documentElement.style.getPropertyValue("--main-color");

Hope someone can help me with this..

erniberni
  • 313
  • 5
  • 17
  • You're on the right track with `getPropertyValue`, but you'll need to compute the styles first. Check out this SO answer: https://stackoverflow.com/a/41725782/1248133 – Amruth Pillai Aug 31 '23 at 09:52
  • Thank you! Didnt believe I was on the right way with that :D – erniberni Aug 31 '23 at 09:56

1 Answers1

1
const wrapper = document.querySelector(".wrapper");
getComputedStyle(wrapper).getPropertyValue("--main-color");
Richard
  • 64
  • 7