I've got a CSS variable that dynamically sets the background color of an SVG element with a CSS variable.
Now I wanted to write a unit test that checks if the color is set properly on the object. Unfortunately, I can't seem to retrieve this value with javascript.
I've created a jsfiddle with my current unsuccessful progress: https://jsfiddle.net/Lmfjdc4e. Upon pressing the checkColor button the wrong fill and background-color attribute is written into the console.
Can I even retrieve the correct computed color of a svg element? If yes how?
Here is the complete source of the jsfiddle:
function checkColor() {
var circle = document.getElementById('circle');
var style = window.getComputedStyle(circle);
var fill = style.getPropertyValue('fill');
var bgColor = style.getPropertyValue('background-color');
console.log(fill) //url(#myGradient)
console.log(bgColor) //rgba(0, 0, 0, 0)
}
.myClass {
--background-color: rgb(255, 0, 0)
}
<svg xmlns="http://www.w3.org/2000/svg" class="myClass" viewBox="0 0 300 200" height="150">
<defs>
<linearGradient id="myGradient">
<stop offset="0" stop-color="var(--background-color)" />
</linearGradient>
</defs>
<circle id="circle" cx="50" cy="165" r="35" fill="url(#myGradient)"/>
</svg>
<button onClick="checkColor()">checkColor</button>