Retrieve a computed svg color with javascript

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: 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="" class="myClass" viewBox="0 0 300 200" height="150">

    <linearGradient id="myGradient">
      <stop offset="0" stop-color="var(--background-color)" />
  <circle id="circle" cx="50" cy="165" r="35" fill="url(#myGradient)"/>

<button onClick="checkColor()">checkColor</button>

93 thoughts on “Retrieve a computed svg color with javascript”

Leave a Comment