Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

301
Views
how to change an attribute of an svg file with javascript?

I know this has been answered before but no solutions are working for me. I want to render an svg file on an html page and access its code elements from javascript. I want to change the attributes of specific elements. Specifically I want to change add an attribute style="fill:#FFFFFF;". Later I will want to remove this. I want to access the element with the id property of the element. I tried doing this with a plethora of javascript code and rendering the svg as an img and an object and nothing works. Is this possible? If so how? Thanks in advance.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

There is no way to change the fill property of an SVG you want to display in an img tag. However, you can change the filter property.

So what you want to do is display the svg file like so:

<img class="svg-icon" src="./your.svg"/>

You have to give your img tag a classname (also, do not set the fill property inline).

Then you can simply apply a filter and the color of the svg will be changed, like so:

.your-icon {
  filter: invert(14%) sepia(95%) saturate(6069%) hue-rotate(360deg) brightness(108%) contrast(117%);
}

The above filter is red. Use this hex to filter converter to find the right color for you: hex to filter.

Here is a codesandbox demo.

about 4 years ago · Juan Pablo Isaza Report

0

You can create a react component for your SVG and control their properties with props in react way:

const SampleIcon = ({fill='red',backgroundColor='white', width='300', height='200'}) => (
  <svg version="1.1"
     width={width} height={height}
     xmlns="http://www.w3.org/2000/svg">
    <rect width="100%" height="100%" fill={backgroundColor} />
    <text x="150" y="125" font-size="60" text-anchor="middle" fill={fill}>SVG</text>
  </svg>
) 

Now use it:

const App = () => (
  <div>
    <SampleIcon fill='green' backgroundColor='#ff0'/>
    <SampleIcon with={400} height={300}/>
  </div>
)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!