Categories
JavaScript Answers

How to change SVG image color with JavaScript?

Spread the love

Sometimes, we want to change SVG image color with JavaScript.

In this article, we’ll look at how to change SVG image color with JavaScript.

How to change SVG image color with JavaScript?

To change SVG image color with JavaScript, we can set the fill attribute value.

For instance, we add an svg with

<svg id="svg" fill="AliceBlue">
  <circle r="50" cx="70" cy="70" />
</svg>

Then we write

const svgElement = document.getElementById("svg");
svgElement.style.fill = "green";

to select the svg element with getElementById.

Then we set the fill attribute’s value by setting svgElement.style.fill to the color we want.

Conclusion

To change SVG image color with JavaScript, we can set the fill attribute value.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *