Change the color of an SVG image using JavaScript

Quoorex
2 min readMar 3, 2021

Scalable Vector Graphics (SVG) are great. They are fast, infinitely resizable, supported by all major browsers and can be freely used by anyone. In short, they are the go-to image format for the web.

Recently, while developing my new website Tailwindize, I obviously opted for using SVGs. Tailwindize displays dynamically colored previews of website components. Because one of those elements includes an SVG, I needed to look for a way to change the color of said SVG using JavaScript.

The code for that image looks something like this:

First, you have to get the hex color code of the color you want to replace. This can be done by opening the image in an image editing program like Inkscape or GIMP. In the case of the example image the hex color of the violet color is #6c63ff.
You'll also have to add a class name to every line referencing the color.

Next up, embed the SVG on the web page like so:

<object id="color-change-svg" data="path/to/svg.svg" type="image/svg+xml" ></object>

Using an object tag is necessary, since images inside img tags cannot be manipulated by JavaScript.

To replace the color of the SVG we will use a bit of JavaScript code:

function changeSVGColor(color) { var svg = document.getElementById("color-change-svg").contentDocument; var elements = svg.getElementsByClassName("primaryColor"); for (var i = 0; i < elements.length; i++) elements[i].style.fill = color; }

You can run this function anywhere in your code (but it has to be run client-side of course) and pass it the new color. The function first gets the SVG by it’s ID color-change-svg and then loops through all of it's elements with the class we assigned earlier ("primaryColor"). For each of those elements, the color is replaced.

I hope this post was of use to you and appreciate all feedback!

Take a look at Tailwindize for a working example of a color-changing SVG.

Originally published at https://quoorex.com on March 3, 2021.

--

--

Quoorex

Developer and full-time learner. Aspiring entrepreneur.