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>

1 thought on “Retrieve a computed svg color with javascript”

  1. You need to get the exact property you are setting. In this case, it will be the following:

    var bgColor = style.getPropertyValue('--background-color');

    The dashes affect the name of the property.


    See the following jsfiddle:

    Evaluating the url on the fly for the fill seems to be the only way to get the correct color.


Leave a Comment