0

I use an SVG like this way:

<image x="0" y="0" width="40" height="40" href="/resource.svg"></image>

This is the resource.svg:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="217px" height="131px" viewBox="-0.5 -0.5 217 131"><defs/><g><ellipse cx="108" cy="65" rx="108" ry="65" fill="rgb(255, 255, 255)" stroke="rgb(0, 0, 0)" pointer-events="all"/><ellipse cx="108" cy="65" rx="40" ry="40" fill="#a0522d" stroke="#6d1f00" pointer-events="all"/></g></svg>

Now, I should dynamicaly change the color of the svg. For this I thought about whether it would be possible to load the SVG completely (inline?) instead of as a link and then replace the values for fill and stroke (with string-replace). If I use it inline, is it possibly also possible to achieve this via CSS?

Can someone help me whether that would be possible and if so, in which direction I have to research further?

BennoDual
  • 5,865
  • 15
  • 67
  • 153
  • One approach is to load the file as string first, then use a DOMParser, keep the resulting XMLDocument somewhere. The contents of the document can be changed using js. Then (if you use an image tag) you can use a data URI for href. – qrsngky Mar 20 '23 at 09:28
  • If you reproduce the SVG inline, you can directly style it using CSS. For external SVGs, some options are laid out in the answers to [this question](https://stackoverflow.com/questions/31128970/how-do-you-style-a-external-svg-with-css). – Robby Cornelissen Mar 20 '23 at 09:39
  • @Robert, you have again closed a question and referred to (very) old answers. It is 2023, all modern Browsers support native JavaScript Web Components. – Danny '365CSI' Engelman Mar 20 '23 at 10:28
  • 3
    @Danny'365CSI'Engelman Feel free to add your answer to that canonical if you wish. If you dislike any of its existing answers, downvote them. – Robert Longson Mar 20 '23 at 10:45
  • Nah, no use, no one reads additional answers, and the accepted jQuery answer from 2012 you link to has **559** Upvotes... – Danny '365CSI' Engelman Mar 20 '23 at 12:56

1 Answers1

0

Remove the fill property from the svg code. This forces it to always be white, the way it is now. Alternatively, if you're working in a framework, you could make the fill property dynamic (e.g. fill={{myProp}}).

paddotk
  • 1,359
  • 17
  • 31