Change the color of an SVG image using JavaScript

Scalable Vector Graphics (SVG) are great. They are fast, infinitely resizable, supported by all major browsers and the file format 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.

Let's use this image as an example (taken from Undraw)

The SVG code for that image looks something like this:

<svg id="ace505a7-e733-4353-98c8-975df89a5922" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" width="728.08199" height="680.00102" viewBox="0 0 728.08199 680.00102"><path id="a55003b0-0446-4784-a3ce-c481a9759178" data-name="Path 339" d="M790.76434,271.5935h-3.736v-102.354a59.24,59.24,0,0,0-59.24-59.24h-216.846a59.24,59.24,0,0,0-59.24,59.24v561.521a59.24,59.24,0,0,0,59.24,59.24h216.85a59.24,59.24,0,0,0,59.24-59.24v-386.31h3.732Z" transform="translate(-235.95901 -109.99949)" fill="#3f3d56"/>
...

Now, to change a color within this SVG, 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 of your choice. I recommend PhotoPea, as it works right in your browser. In the case of the example image, the hex code of the violet color is #6c63ff.

Now that you know the hex code, you will have to open your SVG file. In there, you will need to search for every line referencing the color and add a class name, like class="primaryColor", to them. The image below illustrates what your file should look like in the end:

Adding a class to all lines referencing the color

Next up, update your HTML to include the SVG 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 some 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 its ID color-change-svg and then loops through all of its 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.

Quoorex
Future Entrepreneur. Interested in tech, finance and becoming 1% better every day.
Germany