skip to Main Content

I’m puzzled by SVG fills. I can’t seem to set the fill of a rect with styling, and I can’t set the fill of a rect with Javascript. With this test program, element cal23 is black. Element cal24 is transparent, showing the underlying yellow through, but the Javascript doesn’t set the fill color to red.

document.getElementById('cal23').style.backgroundColor = "red";
document.getElementById('cal24').style.backgroundColor = "red";
console.log('Ran setColor on cal23 and cal24');
body {
  background-color: yellow;
}
<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20.2 11">
  <style>
    #cal23 { fill="none'; }
  </style>

  <rect id="cal23" width="10" height="10" x="0" y="0" stroke-width="0.2" stroke="orange"/>
  <text x="5" y="5" font-size="1.5" text-anchor="middle" fill="black">Test</text>

  <rect id="cal24" width="10" height="10" x="10" y="0" stroke-width="0.2" stroke="pink" fill="none"/>
  <text x="15" y="5" font-size="1.5" text-anchor="middle">Test</text>
</svg>

2

Answers


  1. you can try this property .style.fill. For SVG tag, backcolor style can not work

     <script>
         document.getElementById('cal23').style.fill="red";
         document.getElementById('cal24').style.fill="red";
     <script>
    
    Login or Signup to reply.
  2. Please replace your javascript with this

    <script>
            addEventListener("load", (event) => {;
            document.querySelector('#cal23').style.fill = "red";
            document.querySelector('#cal24').style.fill = "red";
            console.log('Ran setColor on cal23 and cal24');
            })
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search